I don't like slices in D

Jonathan M Davis jmdavisProg at gmx.com
Thu Oct 17 12:05:22 PDT 2013


On Thursday, October 17, 2013 20:31:26 Vitali wrote:
> I repeat my question: "Why does a reallocation accure AFTER a
> resize of the length of a slice, although there is still
> capacity?"

Because it _doesn't_ have the capacity. If you do

writeln(dSlice.capacity);

before incrementing dSlice's length, it'll print out 0. dSlice can't grow in 
place, because if it did, its new elements would overlap with those of dArr;

dArr -> [10, 11, 12]
dSlice -> [10, 11]

++dSlice.length;

dArr -> [10, 11, 12]
dSlice -> [10, 11, 0]

You can't make a slice cover more of another array without reslicing that 
array. e.g.

dSlice = dArr[0 .. $]

dArr -> [10, 11, 12]
dSlice -> [10, 11, 12]

Appending to a slice or increasing its length (which is just appending to it 
with the init value of its element type) is adding a new element which is not 
part of any other array. If there is capacity available, then that will be 
done in place, and the slice will still be a slice of the array that it was 
sliced from. But if there isn't any capacity available (and there isn't in 
your example, because the original array has that space), then the runtime is 
forced to reallocate the slice in order to make space, and then it's no longer 
a slice of the original array.

- Jonathan M Davis


More information about the Digitalmars-d mailing list