Two "references" to dynamic array, why not change both when reallocating?

Simen Kjærås simen.kjaras at gmail.com
Wed Nov 11 13:30:16 UTC 2020


On Wednesday, 11 November 2020 at 10:17:09 UTC, zack wrote:
> I am new to D. Appending to an array can lead to reallocation, 
> that's clear. But why is the "reference" b not changed 
> accordingly to the new position and still points to "old" 
> memory? Why is b not also changed when reallocating array a and 
> the old data getting invalid/freed?
>
> auto a = [55,10,20];
> auto b = a;
> a ~= [99,99,99,99,99,99];
> a[0] = 1;
> assert(b[0] == 1); // could fail
>
> (similar to p.103-104 in "The D Programming language")

The short answer is 'because that's how we've chosen to define 
it'. A more involved answer is that changing every reference is 
prohibitively expensive - it would require the equivalent of a GC 
collection on every reallocation, as references to the array 
could exist anywhere in the program, be that on the stack, heap, 
even on other threads. That's the performance side of it.

Another heavy argument is 'can you make it behave the other way?' 
Currently, that's simple: use a pointer to a slice (T[]*), and 
share that around. I don't see how I would get the current 
behavior if reallocation caused reassignment of all references 
(though admittedly I haven't thought too much about it).

Next up: does b, ending on the same element as a, refer to the 
whole length of a (i.e. should b's length be reassigned when a is 
reallocated?), or is it a slice only referencing the first three 
elements? Either choice is going to be unexpected in some cases.

All in all, there's many reasons to choose the behavior D has 
chosen. There are some drawbacks, but I feel it's the right 
choice.

--
   Simen


More information about the Digitalmars-d-learn mailing list