I didn't expect that you would doubt that the array gets reallocated. Here a code to test:

void appendElement(ref int[] arr, int x) {
        arr ~= x;
}

void removeElement(ref int[] arr, int index) {
        arr = arr[0..index] ~ arr[index+1..$];
}

void main() {
  int* arrPtr1;
  int* arrPtr2;
  int[] arr = [1, 2, 3];

  arr.reserve(7);       // Reserve capacity.
  arr.appendElement(4); // I don't want a realocation
  arrPtr1 = arr.ptr;
  assert(arr.capacity==7);
  arr.removeElement(1); // happen here,
  assert(arr.capacity==3);
  arr.appendElement(5); // but it happens.
  arrPtr2 = arr.ptr;

  assert(arr[1] == 3);
  assert(arr[2] == 4);
  assert(arr[3] == 5);
  assert(arrPtr1 != arrPtr2);  // different arrays <- here
}

I'm not accusing D having a bug here. I'm saying that in my eyes a reallocation of the array referenced by the slice is not useful, when capacity is still available.

@Ali Çehreli: You are right, Go's slices consist of three members. I have read it, although I din't test the code. In http://blog.golang.org/go-slices-usage-and-internals is said: "Slicing does not copy the slice's data. It creates a new slice value that points to the original array. This makes slice operations as efficient as manipulating array indices."

I repeat "[...] as efficient as manipulating array indices." In D this is not the case and can't imagine what purpose can it suit else.

@Meta and @David Eagen: My question is not about creating slices, but about make them shrink and grow without reallocating the referenced array.

Reply via email to