On Wed, 22 Jun 2011 23:38:30 -0400, d coder <dlang.co...@gmail.com> wrote:
Hello List
As per TDPL and D documentation, shrinking a dynamic array should not
relocate it. But that is exactly what is happening.
On shrinking an array, its capacity is getting reduced to 0. Surprisingly
the capacity after a shrink is even less than the length
of the array. As a result the array gets relocated as soon as another
element is added to it.
I have to call reserve again after shrinking it to make sure that the
array
is not relocated.
Is this the expected behavior?
Yes. Capacity is only non-zero for arrays which can safely be extended. If
you shrink an array from length 10 to length 5, the GC is smart enough to
know that that there may be a dangling reference to elements [5..10] and
thus if the length 5 array was appended to, it might stomp on someone
else's data. Long ago, the GC was dumber and it caused a massive hole in
the const/immutable system. If you know that no other aliases exist (i.e.
you're buffering, etc) you can use the function assumeSafeAppend to reset
the capacity. However, I'd strongly recommend switching to Appender
whenever you're tempted to use assumeSafeAppend.