문제

What is the difference in using unnamed namespace and global declaration?
Is there any specific context for using these two?
Can we access unnamed namespace components in external source files?

도움이 되었습니까?

해결책

The point of an unnamed namespace is to provide a unique namespace within a translation unit (= a source file) without requiring an explicit prefix. This allows you to guarantee that your global names won't clash with other, equal global names in other translation units.

For example:

// file1.cpp

namespace
{
    void foo() { /* ... */ }
}

#include "bar.h"

int do_stuff()
{
    foo();
    bar();
    return 5;
}

// file2.cpp

namespace
{
    void foo() { /* ... */ }
}

#include "bar.h"

int do_something else()
{
    bar();
    foo();
    return 12;
}

You can link those two translation units together and know for certain that the two names foo will refer to the function defined in the respective file, and you do not violate the one-definition rule.

Technically, you can think of an unnamed namespace as something like this:

namespace unique_and_unknowable_name
{
    // ...
}

using namespace unique_and_unknowable_name;

Without this tool, the only way you could guarantee a non-violation of ODR would be to use static declarations. However, there's a subtle difference, in that static affects linkage, while namespaces do not.

다른 팁

All names declared inside an unnamed namespace have internal linkage (even names defined with an extern specifier).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top