Reputation: 551
#include <iostream>
class X{
public:
X(int n = 0) : n(n) {}
~X() {std::cout << n;}
int n;
};
void main()
{
X a(1);
const X b(2);
static X c(3);
}
Output is 213
, I thought the destructor uses a LIPO stack, so why it doesn't destruct in a reverse order 321
?
I'm pretty confused and I'd like to know more about it. Thank you so much.
Upvotes: 0
Views: 358
Reputation: 155403
That is LIFO. a
and b
are destructed in reverse order when main
returns, c
is destructed at some undetermined point between when main
returns and the program actually exits (because it's static, tied to the lifetime of the program, not main
itself).
Upvotes: 1
Reputation: 25573
It is calling the destructors in reverse order, but a static variable has a different lifetime.
See Does C++ call destructors for global and class static variables? which explains that variables with a global lifetime are destructed sometime after main
returns.
Upvotes: 1
Reputation: 52471
a
and b
are of automatic duration, destroyed when the block ends. c
is of static duration, destroyed when the program terminates. LIFO order only applies to objects destroyed at the same point in the program.
Upvotes: 3