c++ - 为什么不同 TU 中的 `static` 函数不会破坏 ODR?

标签 c++ static language-lawyer linkage one-definition-rule

ODR 允许我们多次定义相同的内联函数(有一些限制)。

但是,static 函数的更简单情况呢?

// First TU
static int foo() { return 0; }
int bar1() { return foo(); }

// Second TU
static int foo() { return 1; }
int bar2() { return foo(); }

如果我们快速阅读 [basic.def.odr]p4,我们可以天真地得出结论,这将是 UB:

Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program outside of a discarded statement (9.4.1); no diagnostic required.

C++ 标准中的何处指定每个 foo 都是不同的函数,因此即使它们具有相同的名称也不会破坏 ODR?

是否只是阅读 [basic.link]p2.2 的问题(即由于内部链接,名称不指代同一实体,因此 [basic.def.odr]p4 不适用于此处)?或者是否有更多细微差别/规则涉及做出此决定(如 [basic.scope] 中的内容)?

请注意,对于未命名的命名空间,结果很清楚,因为名称已经不同/唯一。

最佳答案

正确 — 尽管它们在本地具有相同的名称,但它们是两个不同的函数/实体,因此没有违规。

[basic.link]/4.3: When a name has internal linkage, the entity it denotes can be referred to by names from other scopes in the same translation unit.

[basic.link]/5: A name having namespace scope has internal linkage if it is the name of a variable, variable template, function, or function template that is explicitly declared static; or [..]

我无法立即找到任何适用的进一步措辞(规范性或其他),但我认为我们不需要任何措辞。

关于c++ - 为什么不同 TU 中的 `static` 函数不会破坏 ODR?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56063976/

相关文章:

c++ - 这篇关于shared_ptr的use_count()的Standardese是什么意思?

c++ - 在查找 namespace 名称期间可以考虑哪些其他名称,而不是 namespace 名称?

你能把 "pointer to a function pointer"转换到 void*

c++ - 如何知道列表中对象的类型?

android - Cocos2d-x 3.14 Android崩溃

php - PHP 中静态匿名函数的意外范围

c++ - 让基类的方法使用继承类的静态成员变量……可能吗?

c++ - 使用 jsoncpp 时从 JSON 中剥离私有(private)数据的最佳方法

c++ - 谁能解释这个程序的类型提升以及为什么输出相同

c++ - C++ 类的静态变量初始化,为什么要包含数据类型?