Problem with associative arrays

Jonathan M Davis jmdavisProg at gmx.com
Sat Mar 19 16:41:19 PDT 2011


On Saturday 19 March 2011 11:12:49 Ali Çehreli wrote:
> On 03/19/2011 10:05 AM, Mafi wrote:
>  > Am 19.03.2011 17:29, schrieb Piotr Szturmaj:
>  >> Shouldn't dynamic array be reference type?
>  > 
>  > Just one note: appending (ar ~= 1) differs from concating (ar = ar ~ 1)
>  > that while the second is guanranteed to reallocate, about the first you
>  > can't be sure. It depends on the GC.
> 
> On the other hand, if the dynamic array is sharing a part of another
> array, extending the dynamic array always breaks the sharing and the
> dynamic array is always relocated.
> 
> void main()
> {
>      int[] a = [ 100, 200, 300 ];
> 
>      // Three slices (aka dynamic arrays) to the first two elements
>      int[] s0 = a[0..2];
>      int[] s1 = a[0..2];
>      int[] s2 = a[0..2];
> 
>      // They share the same first two elements
>      assert(s0.ptr == a.ptr);
>      assert(s1.ptr == a.ptr);
>      assert(s2.ptr == a.ptr);
> 
>      // All of these operations break the sharing
>      ++s0.length;
>      s1 ~= 42;
>      s2 = s2 ~ 43;
> 
>      // Nothing happened to the original
>      assert(a == [ 100, 200, 300 ]);
> 
>      // Because nobody is sharing anymore
>      assert(s0.ptr != a.ptr);
>      assert(s1.ptr != a.ptr);
>      assert(s1.ptr != s0.ptr);
>      assert(s2.ptr != a.ptr);
>      assert(s2.ptr != s0.ptr);
>      assert(s2.ptr != s1.ptr);
> }
> 
> I forgot the name of the feature. Basically, no slice (aka dynamic
> array) can extend into other elements and starts sharing them.

Yes. Dynamic arrays attempt to resize themselves efficiently, so they avoid 
reallocations where they can, but if resizing would cause two arrays to share 
elements which they did not share before that resizing operation, then a 
reallocation of the array being sized takes place, so they no longer share any 
elements even if they did before.

Overall, the way that arrays work works really well, and it's really not all 
that hard to wrap your head around, but it can certainly be confusing at first.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list