C++核心准则SF.6:(只)为转换,基础库或在局部作用域内部使用using namspace指令

时间:2022-07-26
本文章向大家介绍C++核心准则SF.6:(只)为转换,基础库或在局部作用域内部使用using namspace指令,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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