调用由操作符new()分配的内存? [英] Regrow memory allocated by operator new()?
问题描述
如果以这种方式分配,可以重新分配由 operator new()
分配的内存:
char * buf = new char [60];
C ++常见问题说明 new
分配的内存无法由realloc调整大小,因此正确的方法来重新分配由 new
?
方法是使用 std :: vector
或 std :: string
,具体取决于数组的特定用法 - let
new
,您就可以必须重新分配和复制内存。这个简单的模板函数显示了基础: 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;
}
注意,在大多数实现和大多数用例中, realloc()
,减去类型安全。如果这看起来效率不高,好吧, realloc()
可能不会做得更好。
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 memory allocated by new
?
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.
这篇关于调用由操作符new()分配的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!