Search code examples
structinitializationddynamic-arrays

How to create a dynamic arrays of structs in D with the constructor disabled in?


I have code like this:

struct MyStruct {
    immutable int id;
    immutable int value;

    this() @disable;

    this(immutable int pId) {
        id = pId;
        value = getValueById(id);
    }
}

void main() {
    MyStruct structs = new MyStruct[](256); // No default initializer
    foreach(ulong id, MyStruct struct_; structs) {
        structs[id] = MyStruct(id); // Cannot edit immutable members
    }
}

I know I could just initialize a dynamic array and add to it, but I'm interested to see if there is a more efficient way of doing this. I'm mostly concerned about how it'll have to reallocate every time while it really knows how much memory it needs in advance.


Solution

  • Simplest solution is to use the dynamic array and call the .reserve method before doing any appends. Then it will preallocate the space and future appends will be cheap.

    void main() {
        MyStruct[] structs;
        structs.reserve(256); // prealloc memory
        foreach(id; 0 .. 256)
            structs ~= MyStruct(id); // won't reallocate
    }
    

    That's how I'd do it with dynamic arrays, writing to individual members I don't think will ever work with immutability involved like this.

    BTW if you wanted a static array, calling reserve won't work, but you can explicitly initialize it.... to void. That'll leave the memory completely random, but since you explicitly requested it, the disabled default constructor won't stop you. (BTW this is prohibited in @safe functions) But in this case, those immutable members will leave it garbage forever unless you cast away immutability to prepare it soo.. not really workable, just a nice thing to know if you ever need it in the future.