C++核心準則SF.6:(只)為轉(zhuǎn)換,基礎庫或在局部作用域內(nèi)部使用using namspace指令

SF.6: Use?using namespace?directives for transition, for foundation libraries (such as?std), or within a local scope (only)
SF.6:(只)為轉(zhuǎn)換,基礎庫(例如std)或在局部作用域內(nèi)部使用using namspace指令
Reason(原因)
using namespace?can lead to name clashes, so it should be used sparingly. However, it is not always possible to qualify every name from a namespace in user code (e.g., during transition) and sometimes a namespace is so fundamental and prevalent in a code base, that consistent qualification would be verbose and distracting.
using namespace可能導致名稱沖突,因此應該謹慎使用。然而,在用戶代碼中,不可能為所有名稱限定命名空間(例如在轉(zhuǎn)換期間),而且在基礎代碼中,有時命名空間如此基礎和普遍,以至于始終如一地指定命名空間會顯得冗長并分散注意力。
Example(示例)
#include
#include
#include
#include
#include
using namespace std;
// ...
Here (obviously), the standard library is used pervasively and apparently no other library is used, so requiring?std::?everywhere could be distracting.
代碼中,標準庫被普遍使用而且很顯然沒有其他庫被使用,因此到處要求std::容易分散注意力。
Example(示例)
The use of?using namespace std;?leaves the programmer open to a name clash with a name from the standard library
使用using namspadce std;會導致程序完全暴露在和標準庫名稱發(fā)生沖突的危險之下。
#include
using namespace std;
int g(int x)
{
int sqrt = 7;
// ...
return sqrt(x); // error
}
However, this is not particularly likely to lead to a resolution that is not an error and people who use?using namespace std?are supposed to know about?std?and about this risk.
然而,也不是一定能得出這不是一個錯誤的判斷。而且使用std命名空間的人被假定已經(jīng)理解std和這類風險。
Note(注意)
A?.cpp?file is a form of local scope. There is little difference in the opportunities for name clashes in an N-line?.cpp?containing a?using namespace X, an N-line function containing a?using namespace X, and M functions each containing a?using namespace Xwith N lines of code in total.
.cpp文件是局部作用域的一種類型。需要注意的是:在一個N行的.cpp文件中包含using namespae X,在N行函數(shù)中包含using namspace X,一共N行代碼的M個函數(shù)每個都包含一個usning namespace X,這幾種情況下出現(xiàn)問題的機會存在些許不同。
Note(注意)
Don't write?using namespace?in a header file.
不要再頭文件中使用using namespace。
Enforcement(實施建議)
Flag multiple?using namespace?directives for different namespaces in a single source file.
標記在同一個源文件中多次使用using namespace指令導入不同命名空間的情況。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf6-use-using-namespace-directives-for-transition-for-foundation-libraries-such-as-std-or-within-a-local-scope-only
新書介紹
《實戰(zhàn)Python設計模式》是作者最近出版的新書,拜托多多關注!

本書利用Python 的標準GUI 工具包tkinter,通過可執(zhí)行的示例對23 個設計模式逐個進行說明。這樣一方面可以使讀者了解真實的軟件開發(fā)工作中每個設計模式的運用場景和想要解決的問題;另一方面通過對這些問題的解決過程進行說明,讓讀者明白在編寫代碼時如何判斷使用設計模式的利弊,并合理運用設計模式。
對設計模式感興趣而且希望隨學隨用的讀者通過本書可以快速跨越從理解到運用的門檻;希望學習Python GUI 編程的讀者可以將本書中的示例作為設計和開發(fā)的參考;使用Python 語言進行圖像分析、數(shù)據(jù)處理工作的讀者可以直接以本書中的示例為基礎,迅速構建自己的系統(tǒng)架構。
覺得本文有幫助?請分享給更多人。
關注微信公眾號【面向?qū)ο笏伎肌枯p松學習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
