C++核心指导原则: 命名和布局建议

C++ Core Guidelines 整理目录

  1. 哲学部分
  2. 接口(Interface)部分
  3. 函数部分
  4. 类和类层次结构部分
  5. 枚举部分
  6. 资源管理部分
  7. 表达式和语句部分
  8. 性能部分
  9. 并发和并行
  10. 错误处理
  11. 常量和不可变性
  12. 泛型编程
  13. 源文件
  14. 命名和布局建议
  15. 标准库
  16. 其他规则

命名和布局建议

一致的命名方式和代码布局是非常有益的, 无他, 就是避免在代码风格方面引战(像 Go 语言就内置 fmt 命令来保持代码格式化的一致性).

现实中存在非常多的 C++风格, 不可能将他们统一. 所以这里给出的仅仅是些建议, 并非规则.

但是对于个人开发者或者团队来说, 保存统一风格, 将会降低成员的认知负荷, 减小代码维护的难度. 另外从代码观感上来说也会更舒服. 如果从一个文件跳转到另外一个文件时, 发现代码布局不一样, 那对于阅读者来说会产生一些不必要的麻烦. 显得非常不专业.

NL.1: Don’t say in comments what can be clearly stated in code

NL.2: State intent in comments

NL.3: Keep comments crisp

NL.4: Maintain a consistent indentation style

NL.5: Avoid encoding type information in names

NL.7: Make the length of a name roughly proportional to the length of its scope

NL.8: Use a consistent naming style

NL.9: Use ALL_CAPS for macro names only

NL.10: Prefer underscore_style names

NL.11: Make literals readable

NL.15: Use spaces sparingly

NL.16: Use a conventional class member declaration order

NL.17: Use K&R-derived layout

NL.18: Use C++-style declarator layout

NL.19: Avoid names that are easily misread

NL.20: Don’t place two statements on the same line

NL.21: Declare one name (only) per declaration

NL.25: Don’t use void as an argument type

NL.26: Use conventional const notation

NL.27: Use a .cpp suffix for code files and .h for interface files