Difference between using the Stack or the Heap
This question already has an answer here:
First of all - heap and stack are not c++
terms. They are implementation details.
Implementations using stack and heap (which probably most - if not all - do) usually have an upper limit of the stack size. So placing huge variables on the stack can cause stack overflow (which typically leads to unpredictable errors).
However, the stack has benefits over the heap so use it whenever you can - provided you don't put huge variables on the stack.
Notice - that most c++ containers, eg a vector, list, deque, can be placed on the stack without problem because they only put a few bytes on the stack and allocate the real data-container on the heap.
Main "problem" using stack - lifetime of that variables controlled by execution flow not by the developer. Though it is easier when variables are destroyed automatically when they go out of scope in some cases it is necessary and simpler to have data which lifetime controlled by developer, not compiler. Another issue - on standard C++ you can only allocate data on stack which size is known on compile time which is not the case for heap.
链接地址: http://www.djcxy.com/p/14514.html上一篇: 页表如何处理堆栈和堆内存地址?
下一篇: 使用堆栈或堆之间的区别