SF.6: Use using namespace directives for transition, for foundation libraries (such as std), or within a local scope (only)
SF.6:(只)为转换,基础库(例如std)或在局部作用域内部使用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可能导致名称冲突,因此应该谨慎使用。然而,在用户代码中,不可能为所有名称限定命名空间(例如在转换期间),而且在基础代码中,有时命名空间如此基础和普遍,以至于始终如一地指定命名空间会显得冗长并分散注意力。
Example(示例)
#include <string>
#include <vector>
#include <iostream>
#include <memory>
#include <algorithm>
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;会导致程序完全暴露在和标准库名称发生冲突的危险之下。
#include <cmath>
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命名空间的人被假定已经理解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行函数中包含using namspace X,一共N行代码的M个函数每个都包含一个usning namespace X,这几种情况下出现问题的机会存在些许不同。
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
新书介绍
《实战Python设计模式》是作者最近出版的新书,拜托多多关注!
本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。
对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!