Two "references" to dynamic array, why not change both when reallocating?
Mike Parker
aldacron at gmail.com
Wed Nov 11 11:33:36 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")
`b` is not a "reference" to `a`. Consider that under the hood, an
array is a pointer/length pair. `b = a` means that `b` is
initialized such that `b.length == a.length` and `b.ptr ==
a.ptr`. Now when you append to `a`, one of two things can happen:
1. there's no allocation, in which case `a.length != b.length`
and `a.ptr == b.ptr`.
2. there's a reallocation, in which case `a.length != b.length`
and `a.ptr != b.ptr`.
And when you append to `b`, it can also reallocate and `a` will
not be affected.
More information about the Digitalmars-d-learn
mailing list