调用由操作符new()分配的内存? [英] Regrow memory allocated by operator new()?

查看:141
本文介绍了调用由操作符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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆