Constructing a class in-place
rikki cattermole
rikki at cattermole.co.nz
Wed Jul 25 08:11:59 UTC 2018
On 25/07/2018 8:05 PM, Shachar Shemesh wrote:
> Forget the "why" for the moment.
>
> T construct(T, ARGS...)(ARGS args) if( is(T==class) ) {
> auto buffer = new ubyte[__traits(classInstanceSize, T)];
> T cls = cast(T)buffer.ptr;
Allocates the storage space of the fields (both public and private).
> // Is this really the best way to do this?
> buffer[] = cast(ubyte[])typeid(T).initializer()[];
Copies the default initialized state, basically does .init for a struct
but was not too long ago renamed because it conflicted.
> cls.__ctor(args);
Calls a constructor that matches the given arguments.
> return cls;
> }
>
> My question is this: Is this the correct way to do it? There are steps
> here that seem kinda arbitrary, to say the least.
Yes and not arbitrary, read above :)
> I am looking for something akin to C++'s placement new.
>
> Thank you,
> Shachar
Standard solution[0].
[0] https://dlang.org/phobos/std_conv.html#.emplace.4
More information about the Digitalmars-d
mailing list