🐭 C++ 中的常量性修饰

C++ 支持 const 与 constexpr 两种常量性修饰符,它们有些功能是重合的,对于重合的功能,应该优先使用 constexpr,其它地方也要尽可能的使用 constexpr 来提升代码性能。
const:
侧重于函数接口声明,表示不修改入参 (包括 this 指针),是一种接口承诺,const 对象可以在编译时或者运行时计算并初始化。
constexpr:
侧重于定义常量与编译期求值,表示希望对象或者函数在编译期求值,constexpr 对象必须在编译期求值计算并初始化。
const 用例回顾代码示例:

  1. #include <cmath>
  2. #include <iostream>
  3. int main() {
  4. // case 1: const variable calculated at compile time
  5. const int c0 = 1024;
  6. // case 2: const variable calculated at runtime
  7. const int c1 = std::log2(c0);
  8. // case 3: const pointer pointer to const string
  9. const char *const cpc = "constexpr";
  10. // case 4: const reference
  11. const int &rc = c0;
  12. // case 5: const function parameter, promise not changes value of s
  13. auto fun = [](const std::string &s) { return s.length(); };
  14. // case 6: const member function, promise not changes the data member
  15. struct Job {
  16. std::string get_name(void) const { return name_; }
  17. std::string name_;
  18. mutable size_t id_; // mutable data member is an exception to const member function
  19. };
  20. return 0;
  21. }

🐂 constexpr 对象

constexpr 对象是编译期常量,所有的 constexpr 对象都是 const 对象,反之不成立,constexpr 对象必须要能在编译期求值,const 对象没有这个要求。另外,在 C++ 中有些地方必须使用 constexpr 对象,比如数组的大小等。
代码示例 :

  1. #include <array>
  2. #include <iostream>
  3. int main() {
  4. // case 1: all constexpr objects are const object
  5. constexpr int c0 = 42;
  6. std::cout << std::boolalpha << std::is_same_v<decltype(c0), const int> << '\n';
  7. // case 2: constexpr object must be known at compile time
  8. const int c1 = std::abs(-1);
  9. // constexpr int c2 = std::abs(-1); // compile error, value not known at compile time
  10. constexpr int c3 = sizeof(int);
  11. // case 3: array size must be constexpr
  12. constexpr int size = 8;
  13. int arr0[size];
  14. std::array<int, size> arr1;
  15. // case 4: help to detect Undefined Behavior (UB)
  16. constexpr std::array<int, 4> arr{1, 2, 3, 4};
  17. // auto arr40 = arr[4]; // compiles, but trigger UB
  18. // constexpr auto arr41 = arr[4]; // compile error, detected UB
  19. return 0;
  20. }

:::tips constexpr 对象是编译期间初始化的,可能放到代码段,对嵌入式系统尤其重要 :::

🐯 constexpr 函数

constexpr 函数只是编码者所表达的一种期望,它可能在编译期求值,也可能在运行时求值,这个取决于传入的实际参数和一些其它的影响因素。同一个 constexpr 函数能适应不同的上下文语境,编译器会根据上下文语境来生成不一样的代码。
代码示例 :

  1. #include <array>
  2. #include <complex>
  3. #include <iostream>
  4. #include <limits>
  5. constexpr auto pow1(int base, int exp) noexcept {
  6. auto result = 1;
  7. for (auto i = 0; i < exp; ++i) {
  8. result *= base;
  9. }
  10. return result;
  11. }
  12. constexpr int abs1(int v) noexcept {
  13. if (v < 0) {
  14. // constexpr function can only calls constexpr functions
  15. // std::cout is not a constexpr function, so the 'if branch' is not constexpr
  16. std::cout << "Negative v\n";
  17. return -v;
  18. } else {
  19. // this (else) branch still treat as constexpr
  20. return v;
  21. }
  22. }
  23. template <size_t I> auto get(const std::complex<double> &c) {
  24. if constexpr (I == 0) {
  25. return std::fabs(c.real());
  26. } else if constexpr (I == 1) {
  27. return std::fabs(c.imag());
  28. }
  29. return std::numeric_limits<double>::min();
  30. }
  31. int main() {
  32. constexpr int exp1 = 2;
  33. // case 1: exp1 is constexpr, then pow1 called at compile time
  34. std::array<int, pow1(3, exp1)> arr1;
  35. int exp2 = 2;
  36. // case 2: exp2 is not constexpr, then pow1 called at runtime
  37. auto ret1 = pow1(3, exp2);
  38. // constexpr auto ret1 = pow1(3, exp2); // compile error
  39. // case 3: constexpr function can only calls other constexpr functions
  40. constexpr auto ret2 = abs1(3);
  41. // constexpr auto ret2 = abs1(-3); // compile error
  42. auto ret3 = abs1(3);
  43. auto ret4 = abs1(-3); // Negative v
  44. // case 4: constexpr lambda
  45. auto constexprLambda = [](int n) constexpr { return n * 2; };
  46. constexpr auto ret5 = constexprLambda(2);
  47. // case 5: if constexpr
  48. std::complex<double> cd{-1, -2};
  49. std::cout << get<0>(cd) << ' ' << get<1>(cd) << '\n'; // 1 2
  50. return 0;
  51. }

:::tips constexpr 函数的适应性更好:

  1. 当入参为 constexpr 时在编译时求值,提升性能
  2. 当入参为 非 constexpr 时在运行时求值,退化为普通函数

编写一个 constexpr 函数,能自动适配两种情形,很实用,标准库里就有大量的 constexpr 函数 :::

🐰 总结

  1. constexpr 对象是编译期常量,在编译期初始化
  2. constexpr 函数能适应更丰富的上下文语境,可能在编译时求值,也可能在运行时求值
  3. constexpr 是对象或者函数的接口属性