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

C + + 标准中的 $7.3.1.1/2部分写道:

Static 关键字的用法是 中声明对象时弃用 命名空间范围; 未命名的命名空间 提供了一个更好的选择。

我不明白为什么未命名的名称空间被认为是更好的选择?理由是什么?我很早就知道这个标准说的是什么,但是我从来没有认真考虑过这个问题,甚至当我回答这个问题: 未命名名称空间优于静态名称空间?

它是否被认为是优越的,因为它也可以应用于用户定义的类型,正如我在 回答中所描述的那样?还是有其他原因,我不知道?我问这个问题,特别是因为这是我在回答中的推理,而标准可能有其他的想法。

42310 次浏览

One reason may be that static already has too many meanings (I can count at least three). Since an anonymous namespace can encapsulate anything including types, it seems superior to the static solution.

  • 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.

There are two reasons I think:

  • static has two different meanings: at class scope, it means shared by the whole class while at file/function scope it affects the visibility/storage...
  • unnamed namespaces allow to declare new struct, class and typedef

One note though, the commitee backpedaled on this: static is no longer marked as deprecated in n3225.