且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-02 15:55:10


  • 如前所述,命名空间适用于任何事物,而不仅仅是函数和对象。

  • 正如Greg所指出的, static 意味着太多东西了。

  • 命名空间在全球范围内控制可见性的统一和一致的方式。

  • 当使用匿名命名空间时,函数/对象名称会正确地被转换,这样你就可以看到类似匿名命名空间):: 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.