为什么销毁顺序与构造顺序相同,使用静态对象(C++)?
代码是:
#include <iostream>
using namespace std;
class A
{
public:
A() { cout << "A::A" << endl; }
~A() { cout << "A::~" << endl; }
};
class B
{
public:
B() { cout << "B::B" << endl; }
~B() { cout << "B::~" << endl; }
};
int main()
{
B b;
static A a;
return 0;
}
输出是:
B::B
A::A
B::~
A::~
非静态对象b的作用域和静态对象的作用域a在main()函数结束时结束。
问题:为什么构造函数的顺序和析构函数的顺序一样?
回答
静态局部变量将在程序退出时销毁。
块范围静态变量的析构函数在程序退出时调用,但前提是初始化成功。
因此,b将首先在年底destoryed main(),a之后将被销毁。
对于初始化,
在第一次控制通过他们的声明时被初始化
所以b会先在 中初始化main(),然后再a初始化。
- @KrishnaKanthYenumula No, after `main()` ends, there're still some stuffs needs to be done, like destroying objects with static storage duration, including `a` here.