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 declaredstatic
; or [..]
我无法立即找到任何适用的进一步措辞(规范性或其他),但我认为我们不需要任何措辞。
关于c++ - 为什么不同 TU 中的 `static` 函数不会破坏 ODR?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56063976/