Array slices and copy on write

simendsjo simen.endsjo at pandavre.com
Sun Apr 3 07:29:02 PDT 2011


On 03.04.2011 14:55, spir wrote:
> On 04/03/2011 02:29 PM, simendsjo wrote:
>> D will copy the original content if a slice expands, but is the
>> following behavior
>> implementation specific, or part of the specification?
>>
>> auto a = [0,1,2];
>> auto b = a[0..2];
>> a.length = 2; // is a[3] already marked for collection by the gc?
>> assert(a.ptr == b.ptr);
>> b.length += 1; // as b cannot reuse it even though noone is using it
>> assert(a.ptr == b.ptr); // ooops, fails.. b is reallocated
>
> As I understand it (there is no real spec for D), this is consistent
> with the often commented design of D slices.
> People often explain that slices are like views on (implicite or
> explicit) ordinary arrays. Then, change on either is seen by both, just
> like references --*except* when change require resizing.
> Another point of view is that slices somewhat work like copy-on-write:
> there is no actual copy until one variable value is changed, then only
> copy happens --expect when change can happen on place.
>
> Denis

I know the dangers of slices and copy on write. I was thinking of a very 
specific example. I'll try to explain better.

auto a = [0,1,2];
auto b = a[0..2];
a.length = 2;
// a[3] should now not be referenced, but my guess is it's not collected 
by the gc
assert(a.ptr == b.ptr);
b.length += 1;
// b could potentionally use the last part of a instead of reallocating
// Could another implementation reuse a's old memory without reallocating?



More information about the Digitalmars-d-learn mailing list