Problem with associative arrays
bearophile
bearophileHUGS at lycos.com
Sat Mar 19 09:48:46 PDT 2011
Piotr Szturmaj:
> Shouldn't dynamic array be reference type?
They are partially a reference type and partially a value :-)
A D dynamic array is represented with a small struct 2-words long that contains the pointer to the first item of the array and the length of the array (you are able to read them with the .ptr and .length attributes). So when you copy a dynamic array using temp=aa[5] you are copying this little struct. When you perform the temp~=1 you are changing the length just of the copied struct, not of the original aa[5] one (in D1 if temp~=1 induces a realloc then the pointer too gets modified only in the temp struct. In D2 the situation is more complex, unfortunately).
> Is this a bug?
It's clearly a bug-prone characteristic of D2, but it's not a D2 bug, so it's a bug in your code :-( I think future D2 lint tools will have to test for this possible source of bugs too.
Keep in mind that D2 associative arrays have an even worse nature:
void test(int[int] arr, int x) {
arr[x] = x;
}
void main() {
int[int] d;
test(d, 0);
int[int] d0;
assert(d == d0);
d[1] = 1;
test(d, 2);
assert(d == [1: 1, 2: 2]);
}
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list