c++ - 什么时候创建本地静态对象?

标签 c++

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;
}

在本书的这一点上,我还没有介绍 structs 和 classes,但我的理解是函数 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/

相关文章:

c++ - glScissor() 在另一个 glScissor() 中调用

C++:一次读取一个字符,直到行尾不起作用

c++ - C++ 中的 OpenCV : "Unknown Type Name"

c++ - 有没有办法测试 pclose() 是否会成功?

c++ - 当 model_completion 设置为 false 时 Z3 会返回什么?

c++ - 放置额外的圆括号 - 代码无法编译

c++ - 将 unique_ptr 作为引用参数或 const unique_ptr 引用传递

c++ - 在编译时或静态分析期间强制执行 std::nothrow

c++ - 发布版本上的 SFML 图像加载失败 - 文件名损坏

c++ - 构建动态分配的类对象数组