首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >C++核心准则SF.4:在其他声明之前include .h文件

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

作者头像
面向对象思考
发布2020-10-10 10:07:34
发布2020-10-10 10:07:34
6610
举报

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

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

Reason(原因)

Minimize context dependencies and increase readability.

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

Example(示例)

代码语言:javascript
复制
#include <vector>
#include <algorithm>
#include <string>

// ... my code here ...
Example, bad(反面示例)
代码语言:javascript
复制
#include <vector>

// ... my code here ...

#include <algorithm>
#include <string>
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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • SF.4: Include .h files before other declarations in a file
  • Reason(原因)
    • Example, bad(反面示例)
    • Note(注意)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档