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

标签 c++ lifetime static-variables

看下面的代码:

#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”

coliru example


why get1 calls the deconstructor but get2 doesn't?

您看到的析构函数调用发生在程序结束时,当 get1() 中定义的 static T x 被销毁时。

get2() 中定义的 x 不会自动销毁,因为它是堆分配的。您需要删除它,或者更好的是,使用std::unique_ptr

coliru example


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

关于c++ - 函数中静态变量的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42023055/

相关文章:

java - 在 Web 上运行资源匮乏的应用程序

c++ - VeridisBiometricSDK_5.0_Linux 示例: MatchingExample 编译错误

c++ - 如何处理返回指针的生命周期?

rust - 如何注释此 Rust/Calloop 回调代码的生命周期?

rust - 为什么不能在同一结构中存储值和对该值的引用?

c - 为什么此代码不生成重新声明错误?

c++ - 有偏随机数发生器

c - C中静态变量的初始化

python - 如何在Python中完全模拟其他语言的静态类变量的行为

c++ - 模拟按下的快捷方式