dynamic array memory allocation

janderson askme at me.com
Thu May 17 23:14:28 PDT 2007


Greg Weber wrote:
>> AFAIK there's no way to shrink the memory allocated to an array, and the 
>> closest you can get is to call .dup on a slice. This will get you a copy 
>> of part of the array, allowing the original to be garbage collected 
>> (assuming no more references to it exist).
> 
> So here is my attempt.
> 
> bool downsize(T,I)(inout T[] arr, I downSize) {
>     static assert(is(I:size_t),"downsize needs an integer size parameter");
> 
>     if (downSize < arr.length) {
>         auto downsized = arr[0 .. downsize].dup;
>         arr = downsized;
>         return true;
>     }
>     return false;
> }
> 
> 
> bool allocate(T,I)(inout T[] arr, I reservedSize) {
>     static assert(is(I:size_t),"reserve needs an integer size parameter");
>     size_t l = arr.length;
>     if (reservedSize > l) {
>         arr.length = reservedSize;
>         arr.length = l;
>         return true;
>     }
>     return false;
> }
> 

Nice!

I hate to ccomplain however this is not the most efficient way to resize 
an array, unless the compiler is smart enough to remove the copy.

-Joel



More information about the Digitalmars-d mailing list