How to allocate an element of type T with value x in generic code?

Ali Çehreli acehreli at yahoo.com
Wed Apr 3 09:39:13 PDT 2013


On 04/03/2013 08:53 AM, John Colvin wrote:

 > import core.memory : malloc;
 > T x;
 >
 > T* pt = cast(T*)malloc(T.sizeof);
 > *pt = x;
 >
 > note: this is not C malloc, the memory is requested from and managed by
 > the GC.

That assignment will fail in general when the left-hand side has those 
undetermined bits. std.conv.emplace is a safer option but it must be 
used differently for classes.

import std.stdio;
import core.memory;
import std.conv;


T * makeNew(T)(T rhs)
{
     static if (is(T == class)) {
         static assert(false); // not implemented

     } else {
         T * p = cast(T*)GC.calloc(T.sizeof);
         emplace!T(p, rhs);
         return p;
     }
}

struct S
{
     int i;
}

void main()
{
     writeln(*makeNew(42));
     writeln(*makeNew(1.5));
     writeln(*makeNew(S(1)));
}

The program should consider __traits(classInstanceSize) for classes.

Ali



More information about the Digitalmars-d-learn mailing list