🐭 C++ 中的常量性修饰
C++ 支持 const 与 constexpr 两种常量性修饰符,它们有些功能是重合的,对于重合的功能,应该优先使用 constexpr,其它地方也要尽可能的使用 constexpr 来提升代码性能。
const:
侧重于函数接口声明,表示不修改入参 (包括 this 指针),是一种接口承诺,const 对象可以在编译时或者运行时计算并初始化。
constexpr:
侧重于定义常量与编译期求值,表示希望对象或者函数在编译期求值,constexpr 对象必须在编译期求值计算并初始化。
const 用例回顾代码示例:
#include <cmath>#include <iostream>int main() {// case 1: const variable calculated at compile timeconst int c0 = 1024;// case 2: const variable calculated at runtimeconst int c1 = std::log2(c0);// case 3: const pointer pointer to const stringconst char *const cpc = "constexpr";// case 4: const referenceconst int &rc = c0;// case 5: const function parameter, promise not changes value of sauto fun = [](const std::string &s) { return s.length(); };// case 6: const member function, promise not changes the data memberstruct Job {std::string get_name(void) const { return name_; }std::string name_;mutable size_t id_; // mutable data member is an exception to const member function};return 0;}
🐂 constexpr 对象
constexpr 对象是编译期常量,所有的 constexpr 对象都是 const 对象,反之不成立,constexpr 对象必须要能在编译期求值,const 对象没有这个要求。另外,在 C++ 中有些地方必须使用 constexpr 对象,比如数组的大小等。
代码示例 :
#include <array>#include <iostream>int main() {// case 1: all constexpr objects are const objectconstexpr int c0 = 42;std::cout << std::boolalpha << std::is_same_v<decltype(c0), const int> << '\n';// case 2: constexpr object must be known at compile timeconst int c1 = std::abs(-1);// constexpr int c2 = std::abs(-1); // compile error, value not known at compile timeconstexpr int c3 = sizeof(int);// case 3: array size must be constexprconstexpr int size = 8;int arr0[size];std::array<int, size> arr1;// case 4: help to detect Undefined Behavior (UB)constexpr std::array<int, 4> arr{1, 2, 3, 4};// auto arr40 = arr[4]; // compiles, but trigger UB// constexpr auto arr41 = arr[4]; // compile error, detected UBreturn 0;}
:::tips constexpr 对象是编译期间初始化的,可能放到代码段,对嵌入式系统尤其重要 :::
🐯 constexpr 函数
constexpr 函数只是编码者所表达的一种期望,它可能在编译期求值,也可能在运行时求值,这个取决于传入的实际参数和一些其它的影响因素。同一个 constexpr 函数能适应不同的上下文语境,编译器会根据上下文语境来生成不一样的代码。
代码示例 :
#include <array>#include <complex>#include <iostream>#include <limits>constexpr auto pow1(int base, int exp) noexcept {auto result = 1;for (auto i = 0; i < exp; ++i) {result *= base;}return result;}constexpr int abs1(int v) noexcept {if (v < 0) {// constexpr function can only calls constexpr functions// std::cout is not a constexpr function, so the 'if branch' is not constexprstd::cout << "Negative v\n";return -v;} else {// this (else) branch still treat as constexprreturn v;}}template <size_t I> auto get(const std::complex<double> &c) {if constexpr (I == 0) {return std::fabs(c.real());} else if constexpr (I == 1) {return std::fabs(c.imag());}return std::numeric_limits<double>::min();}int main() {constexpr int exp1 = 2;// case 1: exp1 is constexpr, then pow1 called at compile timestd::array<int, pow1(3, exp1)> arr1;int exp2 = 2;// case 2: exp2 is not constexpr, then pow1 called at runtimeauto ret1 = pow1(3, exp2);// constexpr auto ret1 = pow1(3, exp2); // compile error// case 3: constexpr function can only calls other constexpr functionsconstexpr auto ret2 = abs1(3);// constexpr auto ret2 = abs1(-3); // compile errorauto ret3 = abs1(3);auto ret4 = abs1(-3); // Negative v// case 4: constexpr lambdaauto constexprLambda = [](int n) constexpr { return n * 2; };constexpr auto ret5 = constexprLambda(2);// case 5: if constexprstd::complex<double> cd{-1, -2};std::cout << get<0>(cd) << ' ' << get<1>(cd) << '\n'; // 1 2return 0;}
:::tips constexpr 函数的适应性更好:
- 当入参为 constexpr 时在编译时求值,提升性能
- 当入参为 非 constexpr 时在运行时求值,退化为普通函数
编写一个 constexpr 函数,能自动适配两种情形,很实用,标准库里就有大量的 constexpr 函数 :::
🐰 总结
- constexpr 对象是编译期常量,在编译期初始化
- constexpr 函数能适应更丰富的上下文语境,可能在编译时求值,也可能在运行时求值
- constexpr 是对象或者函数的接口属性
