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

时间:2022-07-26
本文章向大家介绍C++核心准则SF.4:在其他声明之前include .h文件,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

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

Reason(原因)

Minimize context dependencies and increase readability.

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

Example(示例)

#include <vector>
#include <algorithm>
#include <string>

// ... my code here ...
Example, bad(反面示例)
#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