c++ - 为什么这些具有外部链接的名称不表示同一实体?

标签 c++ language-lawyer linkage

考虑以下代码片段:

#include <iostream>

int a;
void address_of_a(void) {
    std::cout << &a << std::endl;
}

namespace N {
    int a;
    void address_of_a(void) {
        std::cout << &a << std::endl;
    }   
};

int main(void) {
    address_of_a();
    N::address_of_a();
    return 0;
}

全局命名空间和命名空间 N 被赋予外部链接,因为 N4567 的 3.5 [basic.link] 第 4 段说 p>

An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace has internal linkage. All other namespaces have external linkage...

此外,::aN::a也被赋予外部链接,因为它们不适用于3.5 [basic.link ] 第 3 段,

A name having namespace scope (3.3.6) has internal linkage if it is the name of

  • a variable, function or function template that is explicitly declared static; or,
  • a variable of non-volatile const-qualified type that is neither explicitly declared extern nor previously declared to have external linkage; or
  • a data member of an anonymous union.

但对于 3.5 [basic.link] 第 4 段,

... A name having namespace scope that has not been given internal linkage above has the same linkage as the enclosing namespace if it is the name of

  • a variable; or
  • ...

这意味着它们继承了与全局命名空间和N相同的链接(=外部链接)。总之,它们应表示相同的实体,因为 3.5 [basic.link] 第 9 段说

Two names that are the same (Clause 3) and that are declared in different scopes shall denote the same variable, function, type, enumerator, template or namespace if

  • both names have external linkage or both names have internal linkage and are declared in the same translation unit; and
  • ...

但是,它们似乎表示不同的实体,因为它们的地址不一致。这是为什么?

最佳答案

请参阅第二个项目符号。

Two names that are the same (Clause 3) and that are declared in different scopes shall denote the same variable, function, type, enumerator, template or namespace if

  • both names have external linkage or else both names have internal linkage and are declared in the same translation unit; and

  • both names refer to members of the same namespace or to members, not by inheritance, of the same class; and

  • when both names denote functions, the parameter-type-lists of the functions (8.3.5) are identical; and

  • when both names denote function templates, the signatures (14.5.6.1) are the same.

::aN::a 不引用相同命名空间的成员,因此它们不表示相同的变量。

关于c++ - 为什么这些具有外部链接的名称不表示同一实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35376814/

相关文章:

c++ - 如何使用专用线程类MyThreadClass

C++ 比较两个整数、错误或奇怪的结束

rust - Rust 的句法语法是上下文无关的还是上下文敏感的?

c++ - 如何在不指定数组大小的情况下声明数组,但在 C++ 的类中使用初始化程序?

c++ - C语言联动typedef & templates

linux - ld-linux.so.2 和 linux-gate.so.1 是什么?

c++ - 对 `yylex' 的 undefined reference && 对 `yyin' 的 undefined reference

c++ - 如何正确关闭Qt程序?

c++ - 英特尔 C++ 编译器 (icpc 14.0) : "a derived class is not allowed here"

C++ 单例惰性初始化实现和链接似乎有冲突