C++ local variable destruction order

馋奶兔 提交于 2019-11-27 19:35:35
James Kanze

Within each category of storage classes (except dynamically allocated objects), objects are destructed in the reverse order of construction.

I. About local variables

  1. Local variables are allocated on the Stack.

  2. The Stack is based on a LIFO (Last-In-First-Out) pattern.

  3. So variables are destroyed and deallocated in the reverse order of allocation and construction.

II. About your example

Your function main() is called:

  • x1 is allocated and constructed on the Stack,
  • x2 is allocated and constructed on the Stack

and when the end of the main() function scope is reached:

  • x2 is destroyed and deallocated from the Stack,
  • x1 is destroyed and deallocated from the Stack

III. Moreover

The Stack look like this:

(Behaviour of the Stack seems more understandable with a scheme)

This is a Stack Data Structure behaviour, so local variables stores in Stack as LIFO (Last-In-First-Out) data structure, you can imagine that in a LIFO data structure, the last variable added to the structure must be the first one to be removed. variables are removed from the stack in the reverse order to the order of their addition.

PrisonMonkeys

They are destroyed in reverse allocation order, see this SO question. In this case, this means that x2 will be destroyed before x1.

They will be destroyed following a reverse order of their construction.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!