How to create dynamically sized objects

Straivers via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 29 00:10:44 PDT 2016


Hi,

Say I wanted to create an object that has a string member, and I 
want the string to be allocated with the object contiguously 
instead of as a pointer to another location (as a constructor 
would do). For example:

class C {
     this(int i, string s) {
         this.i = i;
         this.s = s.toUTF16z();
     }

     int i;
     wstring s;
}

I want to allocate memory such that it looks like this:

[32-bit int][s.length * wchar.sizeof bytes]

I've considered using a separate function to create the class, 
but I don't know how setting the length of the string would 
behave. The only solution I can think of would be to have a 
constructor like this:

this(int i, string s, void[] mem) {
     emplace!int(mem.ptr, i);

     auto t = cast(dchar[]) mem[int.sizeof .. $];
     this.s.fill(s.byDChar())
}

Is there a better way to do this?


More information about the Digitalmars-d-learn mailing list