On 3/31/20 2:51 AM, WebFreak001 wrote:
On Tuesday, 31 March 2020 at 02:51:11 UTC, Superstar64 wrote:
I want to be modify an associative array by reference from another function. However null associative arrays are pass by value. How do I generically create an empty associative array?
---
import std.stdio;


void addElement(int[int] data){
    data[0] = 0;
}

void nonempty() {
    int[int] items = [1 : 1];
    writeln(items); // [1 : 1]
    addElement(items);
    writeln(items); // [0 : 0, 1 : 1]
}

void empty(){
    int[int] items = null;
    writeln(items); // []
    addElement(items);
    writeln(items); // []
}

void main(){
    nonempty();
    empty();
}
---

This doesn't only happen with null, you will notice that that function will eventually not add anything if you only add values. This is because by adding values you might reallocate the map at some other place in memory and because it's not ref, the caller won't have the map point to the new reference and still only have the old data.

This is an incorrect assumption. Associative arrays are pImpls. Once the main bucket holder is allocated it will not change. The bucket array may change, but the elements themselves are each individual allocations. So when the bucket array is grown, it might move, but the elements themselves are stationary, and the bucket holder (the main implementation struct) is stationary.

My recommendation to the OP is to follow Vladimir's advice. I do the same thing in my code.

I have considered adding a UFCS method to AAs to initialize them with zero elements, but haven't got around to it.

-Steve

Reply via email to