gpt4 book ai didi

c++ - 给定翻译单元中文件级静态变量的顺序是否始终相同?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:16:53 24 4
gpt4 key购买 nike

我有一个程序分成两个源文件:

example.cpp

#include <iostream>

class A {
public:
A(int x) {
::std::cout << "In A(" << x << ")\n";
}
};

static A first(1);
static A second(2);

例子__main.cpp

int main(int argc, const char *argv[])
{
return 0;
}

这个程序的输出是否保证是:

In A(1)
In A(2)

在所有平台和编译器上?如果是这样,它在标准中的哪个位置这样说?如果我使用命名空间并且 firstsecond 出现在不同的命名空间中,这有关系吗?如果它们不是静态的并且我使用的是匿名命名空间怎么办?

最佳答案

是的,如果声明出现在同一个翻译单元中,则为非本地静态对象定义初始化顺序。

从 C++03 开始​​,

(3.6/2) Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit. [Note: 8.5.1 describes the order in which aggregate members are initialized. The initial-ization of local static objects is described in 6.7. ]

关于c++ - 给定翻译单元中文件级静态变量的顺序是否始终相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8087836/

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