Variable-length stack allocated arrays

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Jan 12 14:22:28 PST 2010


Rainer Deyke wrote:
> Andrei Alexandrescu wrote:
>> template SuperStack(T) {
>>     private T[] buffer;
>>     private enum slackfactor = 2.5;
>>
>>     T[] getBuffer(size_t n) {
>>         buffer.length = buffer.length + n;
>>         return buffer[$ - n .. $];
>>     }
>>
>>     void releaseBuffer(T[] b) {
>>         enforce(b is buffer[$ - b.length .. $]);
>>         buffer.length = buffer.length - b.length;
>>         if (gc.capacity(buffer) > buffer.length * slackfactor) {
>>             // Reallocate buffer to allow collection of slack
>>             buffer = buffer.dup;
>>         }
>>     }
>> }
> 
> Broken design is broken.
> 
> SuperStack!int stack;
> auto buffer0 = stack.getBuffer(100);
> auto buffer1 = stack.getBuffer(10000000); // Reallocates internal array.
> stack.releaseBuffer(buffer1);
> stack.releaseBuffer(buffer0); // Assertion failure.

Yikes, thanks. Now something happened with my news reader - the part of 
your message containing your improved solution got cut off :o).

Andrei



More information about the Digitalmars-d mailing list