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

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

问题描述

C ++ Standard的$ 7.3.1.1/2部分内容如下:

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

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

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意味着已经有太多东西了.
  • 命名空间提供了一种统一且一致的方式来控制全局范围内的可见性.您不必为同一件事使用不同的工具.
  • 使用匿名名称空间时,函数/对象名称将被正确修饰,这使您可以在符号表拆开后在符号表中看到类似于((匿名名称空间):: 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天全站免登陆