0
#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.

Tom S
  • 511
  • 1
  • 4
  • 19

3 Answers3

3

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.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
1

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.

Kiskae
  • 24,655
  • 2
  • 77
  • 74
1

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).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271