gpt4 book ai didi

c++ - 模板如何影响 const 全局变量的链接?

转载 作者:行者123 更新时间:2023-12-02 21:10:26 25 4
gpt4 key购买 nike

the doc说(强调我的):

Any of the following names declared at namespace scope have internal linkage:

  • non-volatile non-template non-inline const-qualified variables (including constexpr) that aren't declared extern and aren't previously declared to have external linkage;

所以我希望 const 模板变量具有外部链接。所以我did a test :

// main.cpp
void other();

template<class T> T var = 1;
template<class T> const T constVar = 1;

int main() {
std::cout << var<int> << ' ' << constVar<int> << std::endl;
other();
}

// other.cpp
template<class T> T var = 2;
template<class T> const T constVar = 2;

void other() {
std::cout << var<int> << ' ' << constVar<int> << std::endl;
}

输出是:

1 1
1 2

第二列用于 constVar,不同的行(从不同的翻译单元打印)它有所不同。这让我认为它实际上具有内部链接,尽管它是一个模板。

我知道我确实违反了 ODR,但只是为了了解发生了什么。

那么constVar实际上有内部链接吗?如果是,文档中突出显示的片段是什么意思?如果不是,那么发生了什么,为什么我们需要这个突出显示的片段?

最佳答案

C++14 N4296 §14.4

A template name has linkage (3.5). [...] Template definitions shall obey the one definition rule (3.2).

C++14 N4296 §3.2.6

Given such an entity named D defined in more than one translation unit, then

  • each definition of D shall consist of the same sequence of tokens; [...]

If D is a template and is defined in more than one translation unit, then the preceding requirements shall apply both to names from the template’s enclosing scope used in the template definition (14.6.3), and also to dependent names at the point of instantiation (14.6.2). If the definitions of D satisfy all these requirements, then the behavior is as if there were a single definition of D. If the definitions of D do not satisfy these requirements, then the behavior is undefined.

模板是隐式内联的,即具有外部链接。发生了什么=未定义的行为。编译器不需要诊断您的代码,并且可能会产生意外/不一致的结果。

关于c++ - 模板如何影响 const 全局变量的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58608299/

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