看下面的代码:
#include <iostream>
using namespace std;
struct T
{
~T()
{
cout << "deconstructor calling\n";
}
};
static T& get1()
{
static T x;
return x;
}
static T& get2()
{
static T& x = *new T;
return x;
}
int main()
{
get1();//calls the deconstructor
get2(); //dosent call the deconstructor
}
为什么 get1
调用解构函数而 get2
不调用?据我所知,静态变量会在您终止程序时销毁!但是为什么在调用get1
之后程序会调用静态变量的解构呢?
我读过类似的帖子:
What is the lifetime of a static variable in a C++ function?
有人在那里说:“函数静态变量的生命周期从程序流第一次遇到声明时开始[0],并在程序终止时结束。”
这似乎不是真的!
最佳答案
get1()
没有调用 ~T()
。证明它的简单方法是多次调用 get1()
:
int main()
{
get1();
get1();
get1();
get2();
get2();
get2();
}
上面的代码片段只会显示一次“deconstructor calling”
。
why
get1
calls the deconstructor butget2
doesn't?
您看到的析构函数调用发生在程序结束时,当 get1()
中定义的 static T x
被销毁时。
get2()
中定义的 x
不会自动销毁,因为它是堆分配的。您需要删除
它,或者更好的是,使用std::unique_ptr
。
顺便说一句,正确的术语是“析构函数”。
关于c++ - 函数中静态变量的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42023055/