C++核心指导原则: 资源管理

C++ Core Guidelines 整理目录

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

资源管理规则

R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization)

R.2: In interfaces, use raw pointers to denote individual objects (only)

R.3: A raw pointer (a T*) is non-owning

R.4: A raw reference (a T&) is non-owning

R.5: Prefer scoped objects, don’t heap-allocate unnecessarily

R.6: Avoid non-const global variables

分配和释放规则

R.10: Avoid malloc() and free()

R.11: Avoid calling new and delete explicitly

R.12: Immediately give the result of an explicit resource allocation to a manager object

R.13: Perform at most one explicit resource allocation in a single expression statement

R.14: Avoid [] parameters, prefer span

R.15: Always overload matched allocation/deallocation pairs

智能指针规则

R.20: Use unique_ptr or shared_ptr to represent ownership

R.21: Prefer unique_ptr over shared_ptr unless you need to share ownership

R.22: Use make_shared() to make shared_ptrs

R.23: Use make_unique() to make unique_ptrs

R.24: Use std::weak_ptr to break cycles of shared_ptrs

R.30: Take smart pointers as parameters only to explicitly express lifetime semantics

R.31: If you have non-std smart pointers, follow the basic pattern from std

R.32: Take a unique_ptr<widget> parameter to express that a function assumes ownership of a widget

R.33: Take a unique_ptr<widget>& parameter to express that a function reseats the widget

R.34: Take a shared_ptr<widget> parameter to express shared ownership

R.35: Take a shared_ptr<widget>& parameter to express that a function might reseat the shared pointer

R.36: Take a const shared_ptr<widget>& parameter to express that it might retain a reference count to the object ???

R.37: Do not pass a pointer or reference obtained from an aliased smart pointer