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.

Ali

Reply via email to