何时应该在堆上分配内存?(C++)

7

我并不完全理解何时应该在堆上分配内存,何时应该在栈上分配。我只知道在栈上分配速度更快,但由于栈的大小限制,我不应该使用它来分配大型数据结构;在决定在哪里分配内存时,还有哪些其他方面需要考虑呢?编辑:实例变量应该在哪里分配?


堆和栈在C语言中的正确使用方法 - David Gladfelter
4个回答

7
  1. 大多数对象应该在栈上分配。生命周期等于作用域。
  2. 如果需要手动控制对象的生命周期,请在堆上分配。
  3. 如果对象很大,栈不足以容纳它,请在堆上分配。
  4. 在情况2和3中使用(名字不太好听的)RAII习惯用法,它允许您在栈上使用操作可能是堆上对象的资源的对象--一个很好的例子是像std::shared_ptr/boost::shared_ptr这样的智能指针。

1
我想要补充一些内容。
  1. 如果你对C++0x感兴趣,你也可以看看unique_ptr<>。我个人认为移动语义非常干净。这不会像shared_ptr那样经常有用,但unique_ptr<>具有一些非常有用的语义,使其保持高效。
- Dragontamer5788

3

当内存需要在当前函数的作用域之外持久存在时,请使用堆。


3

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

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

这段代码将会给你一个大小为numberOfInts的整数指针数组。虽然也有可能在堆栈中实现这个功能,但是这被认为是不安全的,你可能会遇到这个网站名字所描述的错误。


1

只有在编译时知道需要多少存储空间时,才能将堆栈用作存储空间。因此,您可以使用堆栈来:

  • 单个对象(例如,声明本地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.

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接