为什么未命名的命名空间是“优越“替代静态? [英] Why unnamed namespace is a" superior" alternative to static?

查看:113
本文介绍了为什么未命名的命名空间是“优越“替代静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


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

命名空间是更好的选择?有什么理由?我知道这个标准说了很久,但从来没有认真考虑这个问题,即使我回答这个问题:未命名命名空间优于静态的优势?

I don't understand why unnamed namespace is superior alternative? What is the rationale? I knew it for a long time as to what the Standard says, but never gave a serious thought to the question, even when I was replying to this question : Superiority of unnamed namespace over static ?

它被认为是优越的,因为它可以应用于用户定义的类型,如我在 answer 中所述?还是有一些我不知道的其他故事?我问这个,特别是因为这是我的想法在我的答案,而标准可能有别的想法。

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

推荐答案


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

  • 正如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.
    • 这篇关于为什么未命名的命名空间是“优越“替代静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆