gpt4 book ai didi

c++ - 静态析构函数

转载 作者:可可西里 更新时间:2023-11-01 16:35:19 25 4
gpt4 key购买 nike

假设我有:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com