Am 19.03.2011 17:29, schrieb Piotr Szturmaj:
Shouldn't dynamic array be reference type?
uint[][uint] aa;
uint[] temp;
aa[5] = new uint[0];
temp = aa[5]; // copy uint[] reference
temp ~= 1;
assert(temp.length == 1 && temp[0] == 1); // pass
assert(aa[5].length == 1 && aa[5][0] == 1); // fail
Is this a bug?
They are not 'perfect' references. There are pointer+length to/of memory.
If you just pass around these refences they reference the same memory.
If you change the reference in some way (eg appending, concating etc)
the memory could be reallocated.
int[] a, b;
a = [3,4,5];
b = a;
assert(a == b);
assert(a is b); //test for refence equality
//a and b now reference exactly the same memory
//concatening is guaranteed to reallocate
a = a ~ [6, 7];
assert(a == [3, 4, 5, 6, 7]);
assert(b == [3, 4, 5]);
// BUT these 3,4,5 are in different places in memeory
b[0] = 42;
assert(a == [3, 4, 5, 6, 7]);
// when slicing you know reference a subpart of the other array
b = a[0.. 3];
assert(b == [3, 4, 5]);
// changes of b will now be visible in a
// until a or b get reallocated
b[0] = 42;
assert(a == [42, 4, 5, 6, 7]);
assert(b == [42, 4, 5]);
Just one note: appending (ar ~= 1) differs from concating (ar = ar ~ 1)
that while the second is guanranteed to reallocate, about the first you
can't be sure. It depends on the GC.