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?
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.
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).
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.
Within each category of storage classes (except dynamically allocated objects), objects are destructed in the reverse order of construction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With