开发者

Regrow memory allocated by operator new()?

Is it possible to regrow memory allocated by operator new(), when allocated this way:

char* buf = new char[60];

The C++ FAQ states that memory allocated by new cannot be resized by realloc, so what's the correct way to regrow memo开发者_运维问答ry allocated by new?


The correct way is to not do it.

Simply allocate new memory if the previous allocation wasn't big enough.

Or use std::vector which wraps all this functionality very efficiently.


The correct way is to use std::vector or std::string depending on your particular usage of the array--let C++ handle allocation for you.

If you must use new, you'll have to reallocate and copy the memory. This simple templated function shows you the basics:

template <typename T>
T *GrowArray(T *oldArray, size_t oldCount, size_t newCount) {
    T *newArray = new T[newCount];
    if (oldArray) {
        std::copy(oldArray, oldArray + std::min(oldCount, newCount), newArray);
        delete[] oldArray;
    }
    return newArray;
}

Note that, in most implementations and with most use cases, this is essentially what realloc() does, minus the type safety. If this looks inefficient to you, well, realloc() probably isn't doing anything better.


std::vector


The only way is to do a second new, copy the content and then delete the old memory block:

char *tmpbuff = new char[70];
memcpy(tmpbuff, buff, 60 * sizeof(char));
delete [] buff;
buff = tmpbuff;

(No...C++ is not equal to STL, so there is a life without STL :-) )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜