Are objects in anonymous namespace implicitly static?

后端 未结 2 1958
独厮守ぢ
独厮守ぢ 2021-02-12 09:04

From the C++11 standard point of view, is there a technical difference of object status/properties between:

namespace
{
   int foo;
   const int bar = 42;
}


        
相关标签:
2条回答
  • 2021-02-12 09:33

    There is a very big difference: with static, the name has internal linkage; without it, it has external linkage (but is in a namespace you can't cite in another translation unit). The difference isn't always important, but it does come into play in a few cases: if you have a template with an int* parameter, for example, you cannot instantiate it on &foo if foo is declared static.

    EDIT:

    As Steve Jessop has pointed out, this is only true in C++03. C++11 does make a change here. Although I don't know why; I find the C++03 specification more coherent—the namespace something is in shouldn't affect linkage.

    0 讨论(0)
  • 2021-02-12 09:37

    C++11, 3.5/4:

    An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace has internal linkage. All other namespaces have external linkage. A name having namespace scope that has not been given internal linkage above has the same linkage as the enclosing namespace if it is the name of — a variable ...

    So in C++11 both of your foo objects have internal linkage. In C++03, the first one has external linkage.

    Regardless of linkage, it has static storage duration.

    I don't think there's any such thing in the standard as "take the object as if it was marked static", so I can't answer to that. If you find some text in the standard that refers to whether the object is "marked static" and doesn't refer specifically to either linkage or storage duration, then cite it and I can give you an opinion :-)

    0 讨论(0)
提交回复
热议问题