I don't like slices in D

David Nadlinger code at klickverbot.at
Thu Oct 17 12:55:20 PDT 2013


On Thursday, 17 October 2013 at 18:00:20 UTC, Vitali wrote:
> Why the array have to be reallocated after the length of a 
> slice is changed? It makes slices useless.

No, it doesn't. They are extremely helpful, particularly for 
high-performance applications.

> Here a little example (it fails):
>
>   void testSlices() {
>     int[] dArr = [10, 11, 12];
>     int[] dSlice = dArr[0..2];
>     dSlice.length++;
>     assert(dArr[2]==dSlice[2]); // failure
>   }

Of course it does. Increasing the length of an array causes the 
new elements to be default-allocated by the language spec, and as 
dArr and dSlice share the same memory, not reallocating dSlice 
would clobber the third element of dArr.


More information about the Digitalmars-d mailing list