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

网友投稿 848 2022-10-13 20:10:01

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

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

#include using namespace std;void use(){ string s; cin >> s; // fine getline(cin, s); // error: getline() not defined if (s == "surprise") { // error == not defined // ... }}

 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  header, resulting in the popular beginner question "why doesn't getline(cin,s); work?" or even an occasional "strings cannot be compared with ==).

暴露了std::string的定义(“为什么?”会引出一个有趣的细节问题),这种做法的结果是一般的初学者问题:“为什么getlin(cin,s)不动作”,甚至偶然还会出现字符串无法使用==和)比较的问题。可以通过直接包含完全的头文件消除这个需求。

The solution is to explicitly #include :

解决方案就是显式包含

Example, good(范例)

#include #include 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:

// basic_std_lib.h:#include #include #include #include #include

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.

实施建议需要某些关于头文件意图向用户暴露什么和有什么可以让实现有效的知识。直到模块功能可用之前都不会有真正完美的解决方案。

原文链接

​​的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。

觉得本文有帮助?请分享给更多人。

面向对象开发,面向对象思考!

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:C++核心准则SF.3:使用.h文件管理所有在多个源文件中使用的声明
下一篇:r2 类似unix的逆向工程框架和命令行工具
相关文章