C++ Core Guidelines 整理目录
- 哲学部分
- 接口(Interface)部分
- 函数部分
- 类和类层次结构部分
- 枚举部分
- 资源管理部分
- 表达式和语句部分
- 性能部分
- 并发和并行
- 错误处理
- 常量和不可变性
- 泛型编程
- 源文件
源文件规则
SF.1: Use a .cpp
suffix for code files and .h
for interface files if your project doesn’t already follow another convention
- 翻译: 使用
.cpp
为代码文件命名, 使用.h
为接口文件命名(如果项目没有遵循其他约定) - 原因: 保持文件命名一致性有助于提高代码可读性和维护性. 不同的后缀可以帮助快速区分实现文件和接口文件.
SF.2: A header file must not contain object definitions or non-inline function definitions
- 翻译: 头文件中不应包含对象定义或非内联函数定义
- 原因: 避免在多个源文件中包含相同的定义导致链接错误. 头文件应仅包含声明而非定义.
SF.3: Use header files for all declarations used in multiple source files
- 翻译: 在多个源文件中使用的声明应放在头文件中
- 原因: 头文件可以确保所有源文件都能访问到所需的声明, 避免重复定义和编译错误.
SF.4: Include header files before other declarations in a file
- 翻译: 文件中应在其他声明之前包含头文件
- 原因: 确保在使用任何类型或函数之前已经声明它们, 避免编译错误.
SF.5: A .cpp
file must include the header file(s) that defines its interface
- 翻译:
.cpp
文件必须包含定义其接口的头文件 - 原因: 这样可以确保所有的声明都已正确包含, 并且可以在编译时进行检查.
SF.6: Use using namespace
directives for transition, for foundation libraries (such as std
), or within a local scope (only)
- 翻译:
using namespace
指令应仅用于过渡, 基础库(如std
)或局部作用域中 - 原因: 在全局作用域中使用
using namespace
可能导致名称冲突. 局部作用域中使用则更加安全.
SF.7: Don’t write using namespace
at global scope in a header file
- 翻译: 避免在头文件的全局作用域中使用
using namespace
- 原因: 全局作用域中的
using namespace
会影响所有包含该头文件的文件, 增加名称冲突的风险.
SF.8: Use #include
guards for all header files
- 翻译: 所有头文件应使用
#include
保护 - 原因: 防止多次包含同一个头文件导致的重复定义问题.
SF.9: Avoid cyclic dependencies among source files
- 翻译: 避免源文件之间的循环依赖关系
- 原因: 循环依赖会导致编译错误或难以维护的代码结构.
SF.10: Avoid dependencies on implicitly #include
d names
- 翻译: 避免依赖于隐式包含的名字
- 原因: 明确列出所有需要的头文件, 确保代码清晰并减少潜在的编译问题.
SF.11: Header files should be self-contained
- 翻译: 头文件应该是自包含的
- 原因: 自包含的头文件可以独立编译, 便于管理和重用.
SF.12: Prefer the quoted form of #include
for files relative to the including file and the angle bracket form everywhere else
- 翻译: 相对包含文件使用引号形式的
#include
, 对于其他地方则使用尖括号形式 - 原因: 引号形式用于本地文件, 尖括号形式用于系统或第三方库文件, 有助于区分和管理.
SF.13: Use portable header identifiers in #include
statements
- 翻译: 在
#include
语句中使用可移植的头文件标识符 - 原因: 提高代码的可移植性, 使其能在不同平台上正常工作.
SF.20: Use namespace
s to express logical structure
- 翻译: 使用命名空间来表达逻辑结构
- 原因: 命名空间有助于避免名称冲突, 使代码结构更清晰.
SF.21: Don’t use an unnamed (anonymous) namespace in a header
- 翻译: 不要在头文件中使用未命名(匿名)的命名空间
- 原因: 匿名命名空间的内容在每个翻译单元中都是唯一的, 这可能会导致不必要的复杂性和潜在的编译问题.
SF.22: Use an unnamed (anonymous) namespace for all internal/non-exported entities
- 翻译: 对所有内部/非导出实体使用未命名(匿名)的命名空间
- 原因: 匿名命名空间可以使内部使用的符号具有内部链接属性, 避免与其他翻译单元中的同名符号冲突.