Search code examples
arraysvariable-assignmentdsharingdeep-copy

How much information do array variables share?


How much information is copied/shared when I assign one array variable to another array variable?

int[] a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
int[] b = a;
a[0] = 42;
writefln("%s %s", a[0], b[0]);   // 42 42

Apparently, a and b share the same payload, because 42 is printed twice.

a ~= 10;
writefln("%s %s", a.length, b.length);   // 11 10

Appending to a does not change b, so the length does not seem to part of the payload?

b = a;
a ~= 11;
b ~= 42;
writefln("%s %s", a[11], b[11]);   // 11 42

Could a conforming D implementation also print 42 42? Could b ~= 42 overwrite the 11 inside a?

When exactly are a and b detached from each other? Is D performing some COW in the background?


Solution

  • "Arrays" in D don't really exist.

    Slices do.

    Slices are just a pointer and a length. So when you assign them to each other, the pointer and the length get copied. If you modify the target data, then it'll be visible in all instances of the slices -- but if you enlarge one slice, the other one will still be using its old length.

    You normally can't "shrink" the actual length of the array in memory (although you can certainly reduce the slice's length, so it 'sees' less data), so that doesn't cause issues.

    Hope that explains what's going on.