gpt4 book ai didi

c++ - 全局和嵌套匿名命名空间中的歧义访问标识符

转载 作者:行者123 更新时间:2023-12-04 14:46:11 24 4
gpt4 key购买 nike

以下代码:

namespace { constexpr int x = 1; }
namespace X { namespace { constexpr int x = 2; } }
using namespace X;

int main() {
static_assert( ::x == 1 );
}

在 MSVC 中成功编译,MSVC 更喜欢在 ::x 中查找第一个匿名命名空间,而不是 X::(anonymous namespace)

但是,由于选择不明确,GCC 和 Clang 都拒绝了该代码。演示:https://gcc.godbolt.org/z/zPEGzGar3

哪个编译器就在这里?

最佳答案

unnamed namespaces 的引用文献中有一个类似的例子。 :

namespace {
int i; // defines ::(unique)::i
}
void f() {
i++; // increments ::(unique)::i
}

namespace A {
namespace {
int i; // A::(unique)::i
int j; // A::(unique)::j
}
void g() { i++; } // A::(unique)::i++
}

using namespace A; // introduces all names from A into global namespace
void h() {
i++; // error: ::(unique)::i and ::A::(unique)::i are both in scope
A::i++; // ok, increments ::A::(unique)::i
j++; // ok, increments ::A::(unique)::j
}

据此,GCC 和 Clang 因选择不明确而拒绝代码应该是正确的。

Namespaces provide a method for preventing name conflicts in largeprojects.

Symbols declared inside a namespace block are placed in a named scopethat prevents them from being mistaken for identically-named symbolsin other scopes.

如该解释所述,namespace 的引入是为了避免或解决名称冲突。恕我直言,这些代码示例显然试图制造名称冲突。

关于c++ - 全局和嵌套匿名命名空间中的歧义访问标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69999485/

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