C++ local variable destruction order

﹥>﹥吖頭↗ 提交于 2019-11-26 13:48:13

问题


Is there a defined order in which local variables are deallocated in C++ (11) ? To be more concise: In which order will side effects of the destructors of two local variables in the same scope become visible?

e.g.:

struct X{
  ~X(){/*do something*/}
}

int main(){
   X x1;
   X x2;
   return 0;
}

Is x1 or x2 destroyed first when main returns or is the order undefined in C++11?


回答1:


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




回答2:


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)




回答3:


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.




回答4:


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




回答5:


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



来源:https://stackoverflow.com/questions/14688285/c-local-variable-destruction-order

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