Allocating a class within another class during object init w/o passing in an allocator

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Dec 15 11:17:47 PST 2016


On 12/15/2016 06:44 PM, David Zhang wrote:
> It is my understanding that a class can have a struct as one of its
> members, and it will be allocated in-line with the rest of the class'
> members.

Yup.

> My question is this; how might I be able to do this with
> another class? I want to be able to allocate Foo using
> std.experimental.allocator without having to pass in a reference to the
> actual allocator.

Add a fixed-size array with an appropiate size to the class, and use 
std.conv.emplace to construct the object there:

----
class SomeClass {}

class Foo
{
     this()
     {
         import std.conv: emplace;
         sc = emplace!SomeClass(scStorage);
     }

     SomeClass sc;
     void[__traits(classInstanceSize, SomeClass)] scStorage;
}

void main()
{
     import std.experimental.allocator: make;
     import std.experimental.allocator.mallocator: Mallocator;
     auto foo = Mallocator.instance.make!Foo;
}
----

I haven't considered alignment here. I'm not sure if you have to.

The GC will collect the sc object along with the parent Foo. Be cautious 
of that when you allow public access to sc.

You can also replace the sc field with a method that creates the class 
reference on the fly (it's just a cast):

----
class Foo
{
     this()
     {
         import std.conv: emplace;
         emplace!SomeClass(scStorage);
     }

     @property SomeClass sc() { return cast(SomeClass) scStorage.ptr; }
     void[__traits(classInstanceSize, SomeClass)] scStorage;
}
----


More information about the Digitalmars-d-learn mailing list