On Sun, 12 Jun 2011 21:02:05 -0400, Lloyd Dupont <ld-rem...@galador.net> wrote:

But... string being immutable I don't see the point of allocating some space for one..
Am I missing something?

Reserving space for appending does not make that space immutable, yet.

As far as the runtime is concerned, that space is unallocated. Although it can only ever be allocated to have immutable string data, it's not allocated yet, so it can be modified in the future.

Observe:

string s;
assert(s.ptr is null); // string is unallocated
s.reserve(100);

assert(s.length == 0); // reserve doesn't alter the actual string, it just sets up space for it to grow into
assert(s.ptr !is null); // but now it points to a memory block!
auto sptr = s.ptr; // save pointer for later proof...

for(i; 0..20) s ~= "hello"; // make a bunch of hellos
assert(s.length == 100); // yep, we added some data, but
assert(s.ptr is sptr); // it didn't move, so essentially, it "grew" into the existing memory block, that was previously unused.

The reason it works is because the unused space in the block has no references, therefore, even though it is potentially immutable, it doesn't matter that we change it because nobody else knows about it yet.

Note that without the reserve call, s.ptr would not be equal to sptr at the end of the operation, because the runtime would have chosen smaller memory blocks to begin with to store the string.

-Steve

Reply via email to