Strange behavior on shrinking a Dynamic Array -- Capacity reduces to 0
d coder
dlang.coder at gmail.com
Wed Jun 22 20:38:30 PDT 2011
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?
Regards
- Puneet
P.S. Please compile the following code to see yourself.
import std.stdio;
void main() {
uint [] arr;
reserve(arr, 2048);
writeln("After reservation:");
writefln("arr is at: %10s, length: %6s, capacity %6s",
arr.ptr, arr.length, capacity(arr));
// Grow the array
for (size_t i = 0; i < 64; ++i) arr ~= i;
writeln("After appending:");
writefln("arr is at: %10s, length: %6s, capacity %6s",
arr.ptr, arr.length, capacity(arr));
arr.length = 32;
// reserve(arr, 2048); // does not relocate if uncommented
writeln("After setting length:");
writefln("arr is at: %10s, length: %6s, capacity %6s",
arr.ptr, arr.length, capacity(arr));
// grow the array again
for (size_t i = 0; i < 32; ++i) arr ~= i;
writeln("After appending again:");
writefln("arr is at: %10s, length: %6s, capacity %6s",
arr.ptr, arr.length, capacity(arr));
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20110623/1fda4ed9/attachment.html>
More information about the Digitalmars-d
mailing list