length = 0 clears reserve

Jon Degenhardt via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Apr 10 20:00:29 PDT 2017

On Tuesday, 11 April 2017 at 01:59:57 UTC, Jonathan M Davis wrote:
> On Tuesday, April 11, 2017 01:42:32 Jethro via 
> Digitalmars-d-learn wrote:
>> arrays have the ability to reserve but when setting the length 
>> to 0, it removes the reserve!! ;/
>> char[] buf;
>> buf.reserve = 1000;
>> buf.length = 0;
>> assert(buf.capacity == 0);
>> But I simply want to clear the buffer, not change it's 
>> reserve/capacity.
>> I've tried to hack by setting the length to 0 through a 
>> pointer, but that still clears the capacity!
>> I want to do this because I want to be able to reuse the array 
>> without ever reallocating(I'll set the capacity to the max 
>> that will ever be used, I don't have to worry about conflicts 
>> since it will always be ran serially).
>> [snip]
> You can't reuse the memory of a dynamic array by simply setting 
> its length to 0. If that were allowed, it would risk allow 
> dynamic arrays to stomp on each others memory (since there is 
> no guarantee that there are no other dynamic arrays referring 
> to the same memory). However, if you know that there are no 
> other dynamic arrays referrin to the same memory, then you can 
> call assumeSafeAppend on the dynamic array, and then the 
> runtime will assume that there are no other dynamic arrays 
> referring to the same memory.
> [snip]

Another technique that works for many cases is to use an Appender 
(std.array). Appender supports reserve and clear, the latter 
setting the length to zero without reallocating. A typical use 
case is an algorithm doing a series of appends, then setting the 
length to zero and starts appending again.


More information about the Digitalmars-d-learn mailing list