Regrow memory allocated by operator new()?

后端 未结 4 1694
心在旅途
心在旅途 2021-01-22 03:59

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

char* buf = new char[60];

The C++ FAQ states

4条回答
  •  走了就别回头了
    2021-01-22 04:59

    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 
    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.

提交回复
热议问题