C++ local variable destruction order
C++C++11DestructorLocal VariablesC++ Problem Overview
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?
C++ Solutions
Solution 1 - C++
Within each category of storage classes (except dynamically allocated objects), objects are destructed in the reverse order of construction.
Solution 2 - C++
I. About local variables
-
Local variables are allocated on the Stack.
-
The Stack is based on a
LIFO
(Last-In-First-Out
) pattern. -
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)
Solution 3 - C++
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.
Solution 4 - C++
They are destroyed in reverse allocation order, see this SO question. In this case, this means that x2
will be destroyed before x1
.
Solution 5 - C++
They will be destroyed following a reverse order of their construction.
Solution 6 - C++
https://isocpp.org/wiki/faq/dtors#order-dtors-for-locals
isocpp.org has a FAQ about this topic and it says it does in a reverse order. I think that the official site didn't exist when this original question had been asked though.