开发者

Nested unnamed namespace?

开发者 https://www.devze.com 2022-12-16 17:37 出处:网络
When using an unnamed namespace are there any issues if it is nested within another namespace?For example, is there any real difference between Foo1.cpp and Foo2.cpp in the following code:

When using an unnamed namespace are there any issues if it is nested within another namespace? For example, is there any real difference between Foo1.cpp and Foo2.cpp in the following code:

// Foo.h
namespace Foo
{
    void f开发者_如何学JAVAooFunc();
}

// Foo1.cpp
namespace Foo
{
    namespace
    {
        void privateFunction()
        {
            ...
        }
    }

    void fooFunc()
    {
        privateFunction();
    }
}

// Foo2.cpp
namespace
{
    void privateFunction()
    {
        ...
    }
}

namespace Foo
{
    void fooFunc()
    {
        privateFunction();
    }
}


Unnamed namespace could be considered as a normal namespace with unique name which you do not know. According to C++ Standard 7.3.1.1:

An unnamed-namespace-definition behaves as if it were replaced by

  namespace unique { /* empty body */ }
  using namespace unique;
  namespace unique { namespace-body }

where all occurrences of unique in a translation unit are replaced by the same identifier and this identifier differs from all other identifiers in the entire program.

There are no additional issues.


Probably no real difference for your purposes. It makes a difference to where in your cpp file privateFunction is visible. If you add void barFunc() { privateFunction(); } to the end of both files, then Foo2.cpp compiles and Foo1.cpp doesn't.

Normally you wouldn't define external symbols from lots of different namespaces in the same cpp file, so the difference won't come up.

0

精彩评论

暂无评论...
验证码 换一张
取 消