什么时候应该在堆上分配? (C ++)

时间:2010-07-01 22:01:39

标签: c++ memory memory-management

我真的不明白何时应该在堆上分配内存以及何时应该在堆栈上分配。我真正知道的是,在堆栈上分配更快,但由于堆栈较小,我不应该使用它来分配大型数据结构;在决定在哪里分配内存时,我应该考虑哪些其他事项?编辑:我应该在哪里分配实例变量?

4 个答案:

答案 0 :(得分:4)

  1. 在大多数对象的堆栈上分配。终身==范围。
  2. 如果需要手动控制对象的生命周期,请在堆上进行分配。
  3. 如果对象很大且堆栈不够大,请将其分配到堆上。
  4. 在案例2和3中使用(严重名称)RAII惯用法,它允许您使用堆栈上的对象来操作可能是堆上对象的资源 - 一个很好的例子是像std ::这样的智能指针的shared_ptr /升压:: shared_ptr的。

答案 1 :(得分:2)

当内存必须超出当前函数的范围时,请使用堆。

答案 2 :(得分:0)

当您在编译时知道时,您只能将堆栈用作存储空间您需要多大的存储空间。接下来你可以使用堆栈

  • 单个对象(例如您声明了本地intdoubleMyClass temp1;变量
  • 静态大小的数组(就像您声明char local_buf[100];MyDecimal numbers[10];
  • 时所做的那样

当你只知道运行时需要多少空间而你应该 已知缓冲区(如执行char large_buf[32*1024*1024];

然而,正常情况下,很少直接触摸堆,但通常使用为你管理一些堆内存的对象(并且对象可能存在于堆栈中或作为另一个对象的成员 - 其中然后你不关心其他对象在哪里生活)

提供一些示例代码:

{
char locBuf[100]; // 100 character buffer on the stack
std::string s;    // the object s will live on the stack
myReadLine(locBuf, 100); // copies 100 input bytes to the buffer on the stack
s = myReadLine2();
  // at this point, s, the object, is living on the stack - however 
  // inside s there is a pointer to some heap allocated storage where it
  // saved the return data from myReadLine2().
}
// <- here locBuf and s go out-of-scope, which automatically "frees" all
//  memory they used. In the case of locBuf it is a noop and in the case of
//  s the dtor of s will be called which in turn will release (via delete)
//  the internal buffer s used.

所以简要回答你的问题何时不要在堆上分配任何东西(通过new),除非这是通过适当的包装对象。 (std :: string,std :: vector等)

答案 3 :(得分:0)

根据我的经验,当你想在运行时声明一个对象数组的大小时,堆分配是最有用的。

int numberOfInts;
cout << "How many integers would you like to store?: ";
cin >> numberOfInts;
int *heapArray = new int[numberOfInts];

此代码将为您提供一个大小为numberOfInts的尖头数组。它也可以在堆栈中执行此操作,但它被认为是不安全的,并且您可能会收到此站点命名的错误。