D array expansion and non-deterministic re-allocation

dsimcha dsimcha at yahoo.com
Sun Nov 22 06:55:25 PST 2009


== Quote from Ali Cehreli (acehreli at yahoo.com)'s article
> dsimcha Wrote:
> > == Quote from Bartosz Milewski (bartosz-nospam at relisoft.com)'s article
> > > > int[] a = [0];
> > > > auto b = a;
> > > > a ~= 1;
> > > > b ~= 2;
> > > > What is a[1]?
> > > >
> > > > Is this considered "stomping" and requiring a re-allocation?
> > > Can this question be answered without the recourse to implementation, and the
> > MRU cache in particular?
> > > I thought about an abstract definition of "stomping".Something like that: The
> > expanded part of the array is never implicitly shared with any other array. But
> > I'm not sure about this case:
> > > int[] a = [1, 2, 3];
> > > int[] b = a[0..1];
> > > b ~= 4;
> > > what is a[1]?
> > > By my definition, this would be considered stomping, but I couldn't find this
> > example in TDPL.
> >
> > a[1] == 2.  The MRU cache stores both the pointer and the length.  When you
> > attempt to append to b, the MRU is searched.  No array that starts at b.ptr and
> > has length b.length is found.  b is reallocated.
> Consider there is also c:
>   int[] c = b[0..1];
> According to the above definition, after b~=4 'b' would be relocated and b[0]
would be disjoint from c[0].
> Now consider that a's definition is changed to just [ 1 ].
> If I understand this correctly, then b.ptr and b.length would match the original
array, and in this case b ~= 4 operation might not relocate b, and b[0] and c[0]
would refer to the same element.
> A change in 'a' would be defining the relation between b and c.
> Ali

You're right.  Indexing, unlike appending provides no guarantees about stomping,
except that, if none of the arrays involved are resized, then they will point to
the same memory block.  I don't see this as a problem in practice, because it does
not break immutability guarantees, etc.  I've been using D for a year and a half
and never had a bug caused by that.  All you need to do is follow these rules:

1.  If you want a slice to point to the same memory as the original array, make
sure none of the arrays are resized.

2.  If you don't want a slice to point to the same memory as the original array,
use .dup.

3.  If you don't care either way, then do neither.



More information about the Digitalmars-d mailing list