Why an unnamed namespace is a “superior” alternative to static? [duplicate]

丶灬走出姿态 提交于 2019-11-26 07:53:50

问题


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

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.


回答1:


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



回答2:


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.




回答3:


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.




回答4:


Whatever the reasons they had, they changed their minds: http://crazycpp.wordpress.com/2011/01/18/static-keyword-is-back/



来源:https://stackoverflow.com/questions/4977252/why-an-unnamed-namespace-is-a-superior-alternative-to-static

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!