1、用constexpr修饰的函数或变量,表示可以在编译时计算,但是,如果代码中有对于这个函数的调用,并不意味着编译时一定会执行这个函数,只有这个函数返回了一个变量,然后代码中调用这个函数将返回值赋值给constexpr变量,才会导致编译时执行这个语句。
有些傻逼为了用C++的新特性而用新特性,错误的使用constexpr会导致误解,非常蛋疼。
例1:
int main() {
constexpr int x = 100 + 20; // 这句在编译时会执行,和宏有啥区别呢?
static_assert(x == 120, "right");
cout <<"x = "<< x << endl;return 0;
}
例2:
constexpr int factorial(int n)
{
return n <= 1 ? 1 : (n * factorial(n - 1));
}int main() {
constexpr int x = factorial(5); // 这句编译时会执行
static_assert(x == 120, "right");
cout <<"x = "<< x << endl;
return 0;
}int main() {
int x = factorial(5); // 这句编译时不会执行,只有运行时才会执行
cout <<"x = "<< x << endl;
return 0;
}
2、除了上述特性,constexpr修饰的变量和函数,隐式的具备了const和inline的特性。