C++核心准则SF.4:在其他声明之前include .h文件

面向对象思考

共 1879字,需浏览 4分钟

 ·

2020-10-08 03:30

SF.4: Include .h files before other declarations in a file

SF.4:在其他声明之前include .h文件


Reason(原因)

Minimize context dependencies and increase readability.

最小化上下文依赖性并提高可读性。


Example(示例)

#include 
#include
#include

// ... my code here ...
Example, bad(反面示例)
#include 

// ... my code here ...

#include
#include
Note(注意)

This applies to both .h and .cpp files.

本规则.h文件和.cpp文件都适用。


Note(注意)

There is an argument for insulating code from declarations and macros in header files by #including headers after the code we want to protect (as in the example labeled "bad"). However

关于在头文件中隔离代码和声明/宏的方式存在其他观点,这种观点建议在需要保护的代码之后include头文件(就像我们注明反面示例的代码)。然而:

  • that only works for one file (at one level): Use that technique in a header included with other headers and the vulnerability reappears.

    这种方法只适用于一个文件(一层):一旦在一个被其他头文件引用的头文件中使用这个技术,脆弱性会再次出现。

  • a namespace (an "implementation namespace") can protect against many context dependencies.

    命名空间(“实现命名空间”)可以防止很多上下文依赖性。

  • full protection and flexibility require modules.

    完全防止并保持灵活性需要模块功能。


See also(参见):

  • Working Draft, Extensions to C++ for Modules:

    http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4592.pdf

  • Modules, Componentization, and Transition:

    http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0141r0.pdf


Enforcement(实施建议)

Easy.

容易。


原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf4-include-h-files-before-other-declarations-in-a-file


新书介绍

《实战Python设计模式》是作者最近出版的新书,拜托多多关注!

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

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




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

关注微信公众号【面向对象思考】轻松学习每一天!

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



浏览 31
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报