dynamic array memory allocation

Oskar Linde oskar.lindeREM at OVEgmail.com
Wed May 16 09:06:00 PDT 2007


Greg Weber skrev:
>> 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;
> }
> 

Looks good, except possibly the bool return value of allocate, as there 
is no guarantee a reallocation really happened even though it returns 
true. A better way would perhaps be to compare the .ptr and return true 
if it changed.

/Oskar



More information about the Digitalmars-d mailing list