Search code examples
memory-managementdmemory-layout

Dlang - Is there a way to embed objects in objects?


According to the D specification all classes are accessed by reference which would mean that the following class would be layed out in memory as follows.

Pseudocode:

class A
{
    public int c;
    public B b;
}

Memory layout of an object of type A:

4 bytes | int c

(4/8) bytes | address of b

Is there a way to create a class that would embed b directly in A instead of having a reference? Or am I overlooking something?


Solution

  • Scoped turns out to be better than I thought, you can also use emplace which is a bit more cumbersome in this simple case but may come in handy:

    class A {
        import std.conv;
    
        public  B b;
    
        // We can't just use sizeof here because we want the size of the
        // instance, not the reference.
        private void[__traits(classInstanceSize, B)] b_space;
    
        this() {
            b = emplace!B(b_space);
        }
    }