How to allocate an element of type T with value x in generic code?
Ali Çehreli
acehreli at yahoo.com
Wed Apr 3 10:34:49 PDT 2013
On 04/03/2013 10:19 AM, John Colvin wrote:
> On Wednesday, 3 April 2013 at 16:39:18 UTC, Ali Çehreli wrote:
>
>> That assignment will fail in general when the left-hand side has those
>> undetermined bits.
>
> Could you expand on this? I don't fully understand.
In short, there is no object on the left-hand side.
GC.malloc() does not initialize the memory that it allocates. Assignment
involves destroying the lhs object. (It is two operations packaged
together: copy the right-hand side and destroy the left-hand side.)
If the uninitialized bits in the newly-allocated memory were invalid for
T, then the destruction will fail or do something wrong.
The following program is sure to fail because 'fileName' happens to be a
bad string when opAssign() is entered:
// WARNING: Your system may become unresponsive if you execute this program
import std.stdio;
import core.memory;
import std.exception;
import std.array;
struct S
{
string fileName;
this(string fileName)
{
enforce(!fileName.empty);
}
ref S opAssign(S rhs)
{
writefln("Stop using file %s", fileName);
this.fileName = rhs.fileName;
writefln("Start using file %s", fileName);
return this;
}
~this()
{
writefln("Destroying S with %s", fileName);
}
}
void main()
{
auto x = S("abc");
S* pt = cast(S*)GC.malloc(S.sizeof);
*pt = x;
}
Ali
More information about the Digitalmars-d-learn
mailing list