我并不完全理解何时应该在堆上分配内存,何时应该在栈上分配。我只知道在栈上分配速度更快,但由于栈的大小限制,我不应该使用它来分配大型数据结构;在决定在哪里分配内存时,还有哪些其他方面需要考虑呢?编辑:实例变量应该在哪里分配?
我并不完全理解何时应该在堆上分配内存,何时应该在栈上分配。我只知道在栈上分配速度更快,但由于栈的大小限制,我不应该使用它来分配大型数据结构;在决定在哪里分配内存时,还有哪些其他方面需要考虑呢?编辑:实例变量应该在哪里分配?
当内存需要在当前函数的作用域之外持久存在时,请使用堆。
根据我的经验,堆分配在你想要在运行时声明对象数组大小时最有用。
int numberOfInts;
cout << "How many integers would you like to store?: ";
cin >> numberOfInts;
int *heapArray = new int[numberOfInts];
这段代码将会给你一个大小为numberOfInts的整数指针数组。虽然也有可能在堆栈中实现这个功能,但是这被认为是不安全的,你可能会遇到这个网站名字所描述的错误。
只有在编译时知道需要多少存储空间时,才能将堆栈用作存储空间。因此,您可以使用堆栈来:
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.
简短回答你的问题:何时:除非通过适当的包装对象(std::string、std::vector等),否则不要在堆上分配任何东西(通过new
)。