Nope, it doesn't. That's the power of D slices. When you create a dynamic array, the GC allocates a certain amount of memory, let's call it a "page", and sets the array to point to the beginning of this memory. When you append to this array, it simply uses up more of this memory. No reallocation actually occurs until the page is used up, at which point the GC allocates a larger page to store the array in.

Yes, it does. When you take a slice of an array and then append
an element to it, the slice has to be reallocated or the element
in the original array after the end of the slice would be
modified. For example:

auto a = [1,2,3,4,5];
auto b = a[0..3];
b ~= 0;
writeln(a);

If b was not reallocated, the code above would print [1, 2, 3, 0, 5], which is probably not what one would expect. This would cause problems if a function took array as a parameter and then appended to it. If
you passed an array slice to such function you would have a
non-deterministic bug - when the appending would cause reallocation,
everything would be okay, but when it wouldn't, the function would
modifiy the array outside of the slice that was passed to it. Arrays
in D used to work like that IIRC. Someone in this thread mentioned
that you should use assumeSafeAppend for stack implementation (I did
not know about assumeSafeAppend before that). The following code:

auto a = [1,2,3,4,5];
auto b = a[0..3];
assumeSafeAppend(b);
b ~= 0;
writeln(a);

prints [1, 2, 3, 0, 5], so b is not reallocated in this case.

Reply via email to