Array slices and copy on write

spir denis.spir at gmail.com
Sun Apr 3 11:17:06 PDT 2011


On 04/03/2011 04:29 PM, simendsjo wrote:
> 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.

I was trying to explain my views on D's slice semantics, thus showing how/why 
the above behaviour matches it.

> 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?

I think this is how Go does slices (their cap(acity) extends to the end of the 
original array). For me, this would not match D's semantics, but since there is 
no spec AFAIK...

Denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d-learn mailing list