问题描述
我刚刚加入了一个新的C ++软件项目,并且试图了解其设计.该项目频繁使用未命名的名称空间.例如,在类定义文件中可能会发生这样的事情:
I just joined a new C++ software project and I'm trying to understand the design. The project makes frequent use of unnamed namespaces. For example, something like this may occur in a class definition file:
// newusertype.cc
namespace {
const int SIZE_OF_ARRAY_X;
const int SIZE_OF_ARRAY_Y;
bool getState(userType*,otherUserType*);
}
newusertype::newusertype(...) {...
哪些设计考虑因素可能导致人们使用未命名的命名空间?优点和缺点是什么?
What are the design considerations that might cause one to use an unnamed namespace? What are the advantages and disadvantages?
推荐答案
(在下面的内容中,这些内容不再适用于C ++ 11,但确实适用于C ++ 03.C ++ 11几乎没有区别了(如果有的话,它们只是语言律师的区别,我不记得了).
(In the following, the things are stuff that does not apply anymore to C++11, but did apply to C++03. C++11 makes almost no differences anymore (if there are, they are just language lawyer differences which I can't recall).).
未命名的名称空间是使标识符转换单元位于本地的实用程序.它们的行为就像您为命名空间的每个翻译单元选择唯一的名称一样:
Unnamed namespaces are a utility to make an identifier translation unit local. They behave as if you would choose a unique name per translation unit for a namespace:
namespace unique { /* empty */ }
using namespace unique;
namespace unique { /* namespace body. stuff in here */ }
使用空主体的额外步骤很重要,因此您已经可以在名称空间主体中引用在该名称空间中定义的诸如::name
之类的标识符,因为using指令已经发生.
The extra step using the empty body is important, so you can already refer within the namespace body to identifiers like ::name
that are defined in that namespace, since the using directive already took place.
这意味着您可以拥有称为(例如)help
的自由功能,这些自由功能可以存在于多个翻译单元中,并且它们在链接时不会发生冲突.效果几乎与使用C中使用的static
关键字完全相同,您可以将其放入标识符的声明中.未命名的命名空间是一种更好的选择,甚至可以将类型转换单元设置为本地.
This means you can have free functions called (for example) help
that can exist in multiple translation units, and they won't clash at link time. The effect is almost identical to using the static
keyword used in C which you can put in in the declaration of identifiers. Unnamed namespaces are a superior alternative, being able to even make a type translation unit local.
namespace { int a1; }
static int a2;
a
都是本地翻译单元,在链接时不会冲突.但是不同之处在于,匿名名称空间中的a1
获得了唯一的名称.
Both a
's are translation unit local and won't clash at link time. But the difference is that the a1
in the anonymous namespace gets a unique name.
在comeau-computing中阅读出色的文章为什么使用未命名的命名空间而不是静态的命名空间?( Archive.org镜像 ).
Read the excellent article at comeau-computing Why is an unnamed namespace used instead of static? (Archive.org mirror).
这篇关于为什么使用未命名的命名空间,它们有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!