我真的不明白何时应该在堆上分配内存以及何时应该在堆栈上分配。我真正知道的是,在堆栈上分配更快,但由于堆栈较小,我不应该使用它来分配大型数据结构;在决定在哪里分配内存时,我应该考虑哪些其他事项?编辑:我应该在哪里分配实例变量?
答案 0 :(得分:4)
答案 1 :(得分:2)
当内存必须超出当前函数的范围时,请使用堆。
答案 2 :(得分:0)
当您在编译时知道时,您只能将堆栈用作存储空间您需要多大的存储空间。接下来你可以使用堆栈
int
或double
或MyClass 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的尖头数组。它也可以在堆栈中执行此操作,但它被认为是不安全的,并且您可能会收到此站点命名的错误。