D array expansion and non-deterministic re-allocation

dsimcha dsimcha at yahoo.com
Sat Nov 21 15:56:52 PST 2009


== 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.  This is easy to specify:  "The
efficiency of the ~= operator for dynamic arrays is implementation defined but
guaranteed to be no worse than O(N).  An implementation may optimize this
operation to avoid a reallocation on every append.  The current reference
implementation does so.  However, the observable behavior of performing the
operation a ~= b is guaranteed to be equivalent to the observable behavior of
performing the operation a = a ~ b."

Furthermore, the purpose of language design is to create a usable language first
and foremost, and then figure out how to specify it formally and abstractly, not
to create a perfectly bulletproof specification first and foremost and then hope
that results in a usable language.  Again, not saying I particularly like the MRU
cache idea (it has its issues at an implementation level) but I think that
"perfectly specified" has to take a back seat to "works well in practice".



More information about the Digitalmars-d mailing list