C++20新增了两个const相关的关键字,于是当前存在四个相似的关键字:const,constexpr,consteval和constinit。
接下来分别来进行讨论。
第一,经过const修饰的变量具有只读属性,并且初始化发生于运行期。也就是说,若一个变量定义之后不允许被修改,就应该给它加上const。若在一个成员函数中不修改任何成员变量,就应该在成员函数后面加上const。
但是,它也可能发生于编译期,例如以const int代替宏来定义数组大小。
第二,经过constexpr修饰的变量或是函数,既保证只读,又发生于编译期。
然而,只有在参数是常量,和显式地以其返回值来初始化一个编译期常量时,它修饰的函数才会一定发生于编译期。如:
#include <iostream>
constexpr int sqr(int n) {
return n * n;
}
int main() {
// compile time
static_assert(sqr(10) == 100);
// compile time
int array[sqr(10)];
// compile time
constexpr int res = sqr(10);
// compile time or run time
int tmp = sqr(10);
// run time
int a = 10;
int tmp2 = sqr(a);
}
此处,最后两个都可能发生于运行期。
第三,consteval用于创建一个immediate function(立即函数)&#