Is it possible to regrow memory allocated by operator new()
, when allocated this way:
char* buf = new char[60];
The C++ FAQ states
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.