问题描述
我刚刚加入了一个新的 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?
推荐答案
Unnamed namespaces is a utility to make an identifier translation unit 本地.它们的行为就像您会为命名空间的每个翻译单元选择一个唯一名称:
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).
这篇关于为什么使用未命名的命名空间以及它们的好处是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!