为什么要使用未命名的命名空间,它们有什么好处? [英] Why are unnamed namespaces used and what are their benefits?

查看:15
本文介绍了为什么要使用未命名的命名空间,它们有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚加入了一个新的 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).

这篇关于为什么要使用未命名的命名空间,它们有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆