I don't like slices in D

Jesse Phillips Jesse.K.Phillips+D at gmail.com
Thu Oct 17 22:45:30 PDT 2013


On Thursday, 17 October 2013 at 20:03:53 UTC, Vitali wrote:
>   arrPtr1 = arr.ptr;
>   arr.reserve(5);     // reserve capacity
>   arrPtr2 = arr.ptr;
>   assert(arrPtr1 != arrPtr2); // ok, this makes sense
>   assert(arr.capacity==7); // ok, this makes not so
>   // much sense, but it's bigger than 5,
>   // I guess it's ok
>
>   // I reserved extra capacity. I got more
>   // than I needed, but ok.

It will reserve enough memory for the requested size, in doing so 
it will allocate on some hardware friendly boundary. (Others here 
have a better grasp on why and what that is).

>   arr.length--;
>   arrPtr1 = arr.ptr;
>   assert(arrPtr1==arrPtr2); // good, but..
>   assert(arr.capacity==0); // <- WHY ??
>
>   // after the length is reduced the
>   // capacity is set to ZERO, this will
>   // cause the array to be reallocated when
>   // the length is increased by next time,
>   // but what is the purpose of this?

Who owns (arrPtr1 + 4)? You've asked arr to relinquish ownership. 
While arrPtr1&2 can't claim ownership because they are pointers, 
arr2 could exist somewhere in the program. arr2 could have been 
declared:

     auto arr2 = arr[2..$];
     arr2[$-1] = 9;
     assert(arr[$-1] == arr2[$-1]); // both reference same array
     arr.length--;
     arrPtr1 = arr.ptr;
     assert(arrPtr1==arrPtr2);
     assert(arr.capacity==0);
     assert(arr2.capacity==5); //

So to perform the operation:

     arr.length++;

Are you expecting:

     assert(arr[$-1] == arr2[$-1]); // It appears this is true in 
Go

Now take a look at what happens to capacity if we remove the 
shrinking.

   auto arr3 = arr2[1..$];
   assert(arr2.capacity == 5);
   assert(arr3.capacity == 4);
   arr3.length++;
   assert(arr2.capacity == 0);
   assert(arr3.capacity == 4);

Full code: http://dpaste.dzfl.pl/ddcf5ff4

Go code is unsafe, it overwrites your other slice data. I believe 
this was the behavior of D1, is not true in D2 and must not be 
true for immutable arrays such as string.

Go code: http://ideone.com/QEy0v5


More information about the Digitalmars-d mailing list