深入理解C++ const 关键字<六>const 与 constexpr 的区别(现代C++进阶)
C11引入了constexpr常量表达式许多人会将它与const搞混。核心区别const承诺“运行时不可修改”它的值可以在运行时才确定。constexpr承诺“编译期求值”必须能在编译期计算出确定的值用于数组长度、模板参数等#include iostream // 将 getSize 声明为 constexpr使其可以在编译期求值 constexpr int getSize() { return 10; } const int a getSize(); // 正确运行时确定不可修改 constexpr int b getSize(); // 现在正确编译期求值 constexpr int square(int x) { return x * x; } constexpr int c square(5); // 正确编译期计算出 25 int main() { std::cout a a \n; std::cout b b \n; std::cout c c \n; return 0; }