Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ local variable destruction order

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?

like image 298
gexicide Avatar asked Feb 04 '13 13:02

gexicide


People also ask

What is the order in which the objects are destroyed?

When an object goes out of scope or is deleted, the sequence of events in its complete destruction is as follows: The class's destructor is called, and the body of the destructor function is executed. Destructors for nonstatic member objects are called in the reverse order in which they appear in the class declaration.

In what order are objects destroyed c++?

The body of an object's destructor is executed, followed by the destructors of the object's data members (in reverse order of their appearance in the class definition), followed by the destructors of the object's base classes (in reverse order of their appearance in the class definition).

Do local variables get destroyed?

Local variable lifetime: A function's local variables exists only while the function is executing. When the function begins, its local variables and its parameter variables are created in memory, and when the function ends, the local variables and parameter variables are destroyed.


1 Answers

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

like image 77
James Kanze Avatar answered Sep 28 '22 06:09

James Kanze