dynamic array memory allocation

Greg Weber webs.dev at gmail.com
Wed May 16 08:45:19 PDT 2007


> 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;
}




More information about the Digitalmars-d mailing list