Why are unnamed namespaces used and what are their benefits?(为什么要使用未命名的命名空间,它们有什么好处?)
问题描述
我刚刚加入了一个新的 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 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).
这篇关于为什么要使用未命名的命名空间,它们有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么要使用未命名的命名空间,它们有什么好处?
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01