I don't like slices in D
Jonathan M Davis
jmdavisProg at gmx.com
Thu Oct 17 12:48:07 PDT 2013
On Thursday, October 17, 2013 21:23:36 Vitali wrote:
> @Meta and @David Eagen: My question is not about creating slices,
> but about make them shrink and grow without reallocating the
> referenced array.
The only way to make a slice "grow" and slice more of the array that it was a
slice of is to reslice the original array and have the new slice be bigger.
There isn't really any difference between a slice of an array and an array in
D. They're both slices of a block of memory that the runtime owns. It's just
that when you create an array by slicing an existing array, they end up
referring to the same elements until one of them gets reallocated (which
generally occurs when you append to one of them, and there is no available
capacity for that array to grow - either because it's at the end of that block
of memory or because another array refers to the memory past the end of that
array). So, while a slice of an array is effectively a window into that array,
it's really that both arrays are windows into a block of memory that the
runtime owns, and so the runtime isn't going to treat an array differently just
because it was created from slicing another array instead of by explicitly
allocating it.
In general, when you slice arrays, and you want the slice to continue to refer
to the same elements, you only shrink the slice (generally by slicing it
further, though you can also decrement its length), and if you want to
increase the slice and still have it refer to the same elements as the
original array rather than having it reallocate, then you need to reslice the
original array with a greater length rather than manipulating the length of
the current slice.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list