Objects on a stack vs Objects on a heap in C++
This question already has an answer here:
Objects on the stack have the really neat property that the memory that backs them is automatically freed at the end of that stack frame (eg when the function returns.) C++ extends this concept by also calling destructors for all stack objects whenever they fall out of scope (ie they're still freed in the case that an exception is thrown before the function returns.) Since this makes memory management dead simple, and memory management errors have the frustrating combination of being easy to make and hard to detect, stack allocation should be preferred whenever it is feasible.
The downside of stack-allocated objects is...well...they're deleted when the function returns. Sometimes there are legitimate reasons to want the object to live longer. In those cases, you have no choice but to allocate from the heap.
Another point to consider is that stack allocation pretty much has to be a size that is known at the time the software is compiled (but see alloca function available on some platforms.) There are a ton of real world scenarios where you won't know until the program is running how much memory you need. Take for example an address book application. If I am coding such an application, I obviously have no idea how many people the end user is going to want in their address book. The user has to tell the program this information. In this case, you need to have dynamically allocated memory, so you're again looking at heap allocation.
The stack is almost always preferable. Your object may manage data on the heap, like std::string
, in which case the object itself is maintained on the stack (like any other local variable) and the string data is on the heap.
The stack is fast. The heap is slow. The stack is for small data. The heap is for big data.
Hope this helps.
链接地址: http://www.djcxy.com/p/79806.html上一篇: C ++大量向量
下一篇: 堆栈中的对象与C ++中的堆中的对象