問題描述
我剛剛加入了一個(gè)新的 C++ 軟件項(xiàng)目,我正在嘗試了解設(shè)計(jì).該項(xiàng)目經(jīng)常使用未命名的命名空間.例如,類定義文件中可能會(huì)出現(xiàn)這樣的情況:
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(...) {...
哪些設(shè)計(jì)考慮可能會(huì)導(dǎo)致使用未命名的命名空間?有什么優(yōu)點(diǎn)和缺點(diǎn)?
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 本地.它們的行為就像您會(huì)為命名空間的每個(gè)翻譯單元選擇一個(gè)唯一名稱:
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 */ }
使用空主體的額外步驟很重要,因此您已經(jīng)可以在命名空間主體中引用在該命名空間中定義的諸如 ::name
之類的標(biāo)識(shí)符,因?yàn)?using 指令已經(jīng)發(fā)生.
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
的自由函數(shù),這些函數(shù)可以存在于多個(gè)翻譯單元中,并且它們不會(huì)在鏈接時(shí)發(fā)生沖突.其效果幾乎與使用 C 中使用的 static
關(guān)鍵字相同,您可以將其放入標(biāo)識(shí)符的聲明中.未命名的命名空間是一個(gè)更好的選擇,甚至可以將類型轉(zhuǎn)換單元設(shè)為本地.
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;
兩個(gè) a
都是本地翻譯單元,不會(huì)在鏈接時(shí)發(fā)生沖突.但不同的是匿名命名空間中的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 上的優(yōu)秀文章為什么使用未命名命名空間而不是靜態(tài)命名空間? (Archive.org 鏡像).
Read the excellent article at comeau-computing Why is an unnamed namespace used instead of static? (Archive.org mirror).
這篇關(guān)于為什么使用未命名的命名空間以及它們的好處是什么?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!