c++ - 静态析构函数

标签 c++ static destructor

假设我有:

void foo() {
  static Bar bar;
}

C++ 能保证 Bar::Bar() 在 bar 上被调用,而 Bar::~Bar() 从不在 bar 上被调用吗? (直到主要导出之后)。

谢谢!

最佳答案

是的。第一次调用foo()时,会构造Bar bar。然后它将一直可用,直到 main() 完成,之后它将被销毁。

本质上是:

static Bar *bar = 0;
if (!bar)
{
    bar = new Bar;

    // not "real", of course
    void delete_bar(void) { delete bar; }
    atexit(delete_bar);
}

注意我说的是“本质上”;这可能不是实际发生的事情(尽管我认为这离得太远了)。


3.7.1 Static storage duration
1 All objects which neither have dynamic storage duration nor are local have static storage duration. The storage for these objects shall last for the duration of the program (3.6.2, 3.6.3).

关于c++ - 静态析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2278441/

相关文章:

c++ - 使用文本调整 QToolButton 的大小

c++ - 模板化 namespace 和 typedef 是非法的——解决方法?

java - Lambdaj FinalClassArgumentCreators 的应用程序范围的配置。在哪里以及如何做?

c++ - 是否存在 static_warning?

c++ - 条件运算符的局限性? :

c++ - 我如何在我的代码中使用 openMP?

c++ - 使用共享库中的多态对象安全吗?

android - 从后台返回应用程序时,保存在单例中的静态数据有时为空

c++ - 如何获取析构函数的成员函数指针?

destructor - 为什么这行代码会出现缓冲区溢出错误?