不具名的命名空间(unnamed namespaces)

众所周知,命名空间是用来防止对象的重复定义的。
如下,编译不会出错:

namespace n1 {
    int x;
}
namespace n2 {
    int x;
}
//访问
n1.x;
n2.x;

上面是具名的名字空间,不具名的名字空间也是防止对象重复定义用,只是他没有名字而已。

file1.cpp:
namespace {
    //变量x和方法fun只在file1.cpp可见
    int x;
    int fun();
}
file2.cpp
namespace {
    int x;
    int fun();
}
//在本地直接使用即可
x = 1;
不知道名字当然无法访问了。不具名空间依然是外链接的,但是外界由于不知道名字所以无法访问,这样就具有了内链接的特性。使用不具名空间是为了保持对象的局部性。
可以用不具名命名空间替代static(staitc是内链接的)。

不能在.h 文件中使用不具名命名空间。因为两个头文件都使用不具名命名空间定义了一样的对象,包含进来依然会有冲突。

MSDN:
anonymous or unnamed namespaces
You can create an explicit namespace but not give it a name:

    namespace {
        int MyFunc(){}
    }

This is called an unnamed or anonymous namespace and it is useful when you want to make variable declarations invisible to code in other files (i.e. give them internal linkage) without having to create a named namespace. All code in the same file can see the identifiers in an unnamed namespace but the identifiers, along with the namespace itself, are not visible outside that file—or more precisely outside the translation unit.

你可能感兴趣的:(不具名的命名空间(unnamed namespaces))