为什么未命名的命名空间是“优越"的?替代静态?

2022-01-14 00:00:00 namespaces standards c++ iso

C++ 标准中的 $7.3.1.1/2 部分内容如下:

The section $7.3.1.1/2 from the C++ Standard reads:

static关键字的使用是在 a 中声明对象时不推荐使用命名空间范围;未命名的命名空间提供了更好的选择.

The use of the static keyword is deprecated when declaring objects in a namespace scope; the unnamed-namespace provides a superior alternative.

我不明白为什么一个未命名的命名空间被认为是更好的选择?理由是什么?我很早就知道标准的内容,但我从未认真考虑过,即使我在回答这个问题时也是如此:未命名命名空间优于静态?

I don't understand why an unnamed namespace is considered a superior alternative? What is the rationale? I've known for a long time as to what the standard says, but I've never seriously thought about it, even when I was replying to this question: Superiority of unnamed namespace over static?

正如我在 回答?还是还有其他一些我不知道的原因?我问这个,特别是因为这是我在回答中的推理,而标准可能有其他考虑.

Is it considered superior because it can be applied to user-defined types as well, as I described in my answer? Or is there some other reason as well, that I'm unaware of? I'm asking this, particularly because that is my reasoning in my answer, while the standard might have something else in mind.

推荐答案

  • 正如您所提到的,命名空间适用于任何事物,而不仅仅是函数和对象.
  • 正如 Greg 所指出的,static 已经意味着太多东西了.
  • 命名空间提供了一种统一且一致的方式来控制全局范围内的可见性.您不必为同一件事使用不同的工具.
  • 当使用匿名命名空间时,函数/对象名称会被正确地修饰,这使您可以在去修饰后在符号表中看到类似(anonymous namespace)::xyz"的内容,而不仅仅是xyz"带有静态链接.
  • 正如下面评论中所指出的,不允许使用静态的东西作为模板参数,而使用匿名命名空间就可以了.
  • 更多?可能,但我现在想不出别的.
    • As you've mentioned, namespace works for anything, not just for functions and objects.
    • As Greg has pointed out, static means too many things already.
    • Namespaces provide a uniform and consistent way of controlling visibility at the global scope. You don't have to use different tools for the same thing.
    • When using an anonymous namespace, the function/object name will get mangled properly, which allows you to see something like "(anonymous namespace)::xyz" in the symbol table after de-mangling, and not just "xyz" with static linkage.
    • As pointed out in the comments below, it isn't allowed to use static things as template arguments, while with anonymous namespaces it's fine.
    • More? Probably, but I can't think of anything else right now.

相关文章