函数中静态变量的生命周期

MEM*_*EMS 0 c++ static-variables lifetime

请参阅以下代码:

#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 
}
Run Code Online (Sandbox Code Playgroud)

为什么get1叫解构主义但get2不是?据我所知,当你终止程序时,静态变量会被破坏!但为什么在调用get1程序后调用静态变量的解构?

我有一个类似帖子的阅读:

C++函数中静态变量的生命周期是多少?

有人说:"函数静态变量的生命周期首次开始[0]程序流遇到声明,它在程序终止时结束."

这似乎不是真的!

Vit*_*meo 6

get1()不打电话~T().证明它的简单方法是get1()多次调用:

int main()
{
    get1();
    get1();
    get1();
    get2();  
    get2();  
    get2();  
}
Run Code Online (Sandbox Code Playgroud)

上面的代码段只会显示"deconstructor calling"一次.

coliru的例子


为什么get1叫解构主义但get2不是?

你看到的析构函数调用是在程序结束时发生的,当static T x定义的内容get1()被销毁时.

x定义get2(),因为它是不会被自动销毁堆分配.你需要delete它,或者更好的是,使用它std::unique_ptr.

coliru的例子


顺便说一句,正确的术语是"析构函数".