C++核心指导原则: 常量和不可变性

C++ Core Guidelines 整理目录

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

常量和不可变性

Con.1: By default, make objects immutable

Con.2: By default, make member functions const

Con.3: By default, pass pointers and references to consts

Con.4: Use const to define objects with values that do not change after construction

void f()
{
    int x = 7; // 默认 x 是可变的
    const int y = 9; // y 是常量, 不会被修改

    for (;;) {
        /* ... */
    }
    // ...
}

Con.5: Use constexpr for values that can be computed at compile time

constexpr double f(int x) { /* ... */ }

double x = f(2);            // 运行时计算
const double y = f(2);      // 运行时计算
constexpr double z = f(2);  // 编译时计算

相关帖子

  1. C++ constexpr, consteval 和 constinit 简要介绍
  2. C++ 中的 const 和 constexpr: 深入对比与最佳实践