gpt4 book ai didi

c++ - 单一定义规则是否强制创建单个静态函数变量?

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

例如,考虑这个 header :

#include <iostream>

template<bool = true>
struct A {
A() {
static int x;
std::cout << &x << "\n";
}
};

static A<> a;

如果我有两个不同的 C++ 文件(包括这个文件)怎么办 - 它会打印两次相同的地址吗?更重要的是,如果 x 是具有非平凡构造函数的不同类型的对象,是否可以保证它只运行一次?

最佳答案

标准 [C++11 14.8/2] 说

Each function template specialization instantiated from a template has its own copy of any static variable.

我假设(并真诚地希望)模板类的成员函数以同样的方式对待,尽管我找不到这样说的特定语言。

无论如何,除了与在多线程上下文中初始化静态变量相关的常见风险之外,我相信这会很好。 A<true>::A() (和内部“static int A<true>::A::x”)将被标记为弱符号,并且将在链接时选择一个版本,与任何其他模板相同。 (显然, A<false> 的实例化与 A<true> 不同。)

编辑评论:

[3.2/5] 部分似乎涵盖了对不同翻译单元的担忧,定义了 ODR:

If D is a template and is defined in more than one translation unit, then... [providing the definitions are identical]... the program shall behave as if there were a single definition of D.

实际要求更多的是语言法律(实例化时的相关名称必须相同,等等),但我认为这是让你清楚的一点:-)

关于c++ - 单一定义规则是否强制创建单个静态函数变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20484885/

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