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

Reply via email to