前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则​SF.10:避免依赖隐式包含的名称

C++核心准则​SF.10:避免依赖隐式包含的名称

作者头像
面向对象思考
发布2020-10-30 11:25:22
5450
发布2020-10-30 11:25:22
举报

SF.10: Avoid dependencies on implicitly #included names

SF.10:避免依赖隐式包含的名称

Reason(原因)

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(反面示例)

代码语言:javascript
复制
#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(范例)

代码语言:javascript
复制
#include <iostream>
#include <string>
using namespace std;

void use()
{
    string s;
    cin >> s;               // fine
    getline(cin, s);        // fine
    if (s == "surprise") {  // fine
        // ...
    }
}
Note(注意)

Some headers exist exactly to collect a set of consistent declarations from a variety of headers. For example:

有些头文件只是为了汇集了一套选自大量头文件的声明而存在,例如:

代码语言:javascript
复制
// 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"

现在用户可以使用一条包含指令引入一套声明:

代码语言:javascript
复制
#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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-10-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • SF.10: Avoid dependencies on implicitly #included names
    • Reason(原因)
      • Note(注意)
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档