I don't like slices in D

Steven Schveighoffer schveiguy at yahoo.com
Tue Jan 14 20:05:50 PST 2014


On Thu, 17 Oct 2013 23:45:18 -0400, Ali Çehreli <acehreli at yahoo.com> wrote:

> On 10/17/2013 03:33 PM, Sean Kelly wrote:
>
>  > I'd be curious to see if this would ever relocate:
>  >
>  > int[] dArr = [10,11,12];
>  > const(int)[] dSlice = dArr[0..2];
>  > dSlice.length++;
>  >
>  > It shouldn't, since growing a const slice can never clobber the
>  > underlying array,
>
> However, according to spec, the appended elements must be 0. There is an  
> optimization opportunity if the elements beyond dSlice's end were all  
> zeros and if the type system guaranteed that they were immutable. Only  
> then dSlice's relocation could be elided.

(catching up on D forums)

Ali is correct, the above code will always reallocate. Underneath, the  
array runtime has no specialized code to deal with const, only shared.

In reality, the dSlice.length++ line is equivalent to doing:

dSlice ~= int.init;

for all flavors of const.

-Steve


More information about the Digitalmars-d mailing list