SF.10:避免依赖隐式包含的名称
Avoid surprises. Avoid having to change #includes if an #included header changes. Avoid accidentally becoming dependent on implementation details and logically separate entities included in a header.
避免意外。避免因为包含的头文件的变更引起包含指令的变化。避免偶然依赖实现细节并从逻辑上分离某个头文件中包含的实体。
Example, bad(反面示例)
#include <iostream>
using namespace std;
void use()
{
string s;
cin >> s; // fine
getline(cin, s); // error: getline() not defined
if (s == "surprise") { // error == not defined
// ...
}
}
<iostream> exposes the definition of std::string ("why?" makes for a fun trivia question), but it is not required to do so by transitively including the entire <string> header, resulting in the popular beginner question "why doesn't getline(cin,s); work?" or even an occasional "strings cannot be compared with ==).
<iostream>暴露了std::string的定义(“为什么?”会引出一个有趣的细节问题),这种做法的结果是一般的初学者问题:“为什么getlin(cin,s)不动作”,甚至偶然还会出现字符串无法使用==和)比较的问题。可以通过直接包含完全的<string>头文件消除这个需求。
The solution is to explicitly #include <string>:
解决方案就是显式包含<string>:
Example, good(范例)
#include <iostream>
#include <string>
using namespace std;
void use()
{
string s;
cin >> s; // fine
getline(cin, s); // fine
if (s == "surprise") { // fine
// ...
}
}
Some headers exist exactly to collect a set of consistent declarations from a variety of headers. For example:
有些头文件只是为了汇集了一套选自大量头文件的声明而存在,例如:
// basic_std_lib.h:
#include <string>
#include <map>
#include <iostream>
#include <random>
#include <vector>
a user can now get that set of declarations with a single #include"
现在用户可以使用一条包含指令引入一套声明:
#include "basic_std_lib.h"
This rule against implicit inclusion is not meant to prevent such deliberate aggregation.
本规则反对隐式包含,但无意阻止这种有意识的组合。
Enforcement(实施建议)
Enforcement would require some knowledge about what in a header is meant to be "exported" to users and what is there to enable implementation. No really good solution is possible until we have modules.
实施建议需要某些关于头文件意图向用户暴露什么和有什么可以让实现有效的知识。直到模块功能可用之前都不会有真正完美的解决方案。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf10-avoid-dependencies-on-implicitly-included-names