C++ Primer 一书的第 6.1.1 章说:
Each local
static
object is initialized before the first time execution passes through the object’s definition. Local statics are not destroyed when a function ends; they are destroyed when the program terminates.
为了检查这一点,我运行了以下代码:
#include <iostream>
using std::clog;
using std::endl;
struct Bar {
Bar() {
clog << "constructing Num object" << endl;
}
int i = 0,
j = 0;
~Bar() {
clog << "destructing Num object" << endl;
}
};
void foo() {
clog << "foo() started" << endl;
static Bar b;
return;
}
int main() {
if (true) {
clog << "if-statement started" << endl;
foo();
}
clog << "if-statement exited" << endl;
return 0;
}
在本书的这一点上,我还没有介绍 struct
s 和 class
es,但我的理解是函数 Bar()
在创建时将一条消息记录到标准输出,并且 b
被默认初始化。如果是这样,那为什么输出显示对象在控制到达static Bar b;
时被构造/初始化,而不是在到达这条语句之前?
输出:
if-statement started
foo() started
constructing Num object
if-statement exited
destructing Num object
最佳答案
When are local static objects created?
正如你的书所说:“在第一次执行通过对象的定义之前”。
更准确地说,标准的措辞是:
Dynamic initialization of a block-scope variable with static storage duration or thread storage duration is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization.
我认为你对“之前”这个词太执着了。 🙂
关于c++ - 什么时候创建本地静态对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63114889/