When should I allocate on the heap? (C++)
I don't really understand when I should be allocating memory on the heap and when I should allocate on the stack. All I really know is that allocating on the stack is faster, but since the stack is smaller I shouldn't use it to allocate large data structures; what other things should I take into account when deciding where to allocate memory? Edit: where should I allocate instance variables?
当内存必须超出当前函数的范围时才使用堆。
You can only use the stack as storage space when you know at compile time how big the storage you are going to need is. It follows that you can use the stack for
int
or double
or MyClass temp1;
variable char local_buf[100];
or MyDecimal numbers[10];
You have to use the heap ("free store") when you only know how much space you need at runtime and you should probably use the heap for large statically known buffers (like don't do char large_buf[32*1024*1024];
)
Normally however, you very seldomly should touch the heap directly, but normally use objects that manage some heap memory for you (and the object possibly lives on the stack or as member of another object - where you then don't care where the other object lives)
To give some example code:
{
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.
So to give a short answer to your question when : Don't allocate anything on the heap (via new
) unless this is done via an appropriate wrapper object. (std::string, std::vector, etc.)
上一篇: 我该如何重载新操作符才能在堆栈上分配?
下一篇: 我应该在什么时候分配堆? (C ++)