作为关键字constexpr
暗示 const
并且它也可以在编译时计算,这是否意味着现在将变量声明为 const
没有意义,我们应该始终将它们声明为 constexpr
?
最佳答案
and it can also be calculated at compile time, does it mean that now declaring variables as
const
doesn't make sense and we should always declare them asconstexpr
?
并且必须在编译时计算(忽略 as-if rule )。
所以你不能申报
constexpr
用运行时已知值初始化的变量。但是你可以申报const
.例如:您不能声明
bar
constexpr
int foo;
std::cin >> foo;
constexpr int bar = foo; // compilation error
但你可以申报 const
int foo;
std::cin >> foo;
const int bar = foo; // compile
关于c++ - 在将 constexpr 添加到语言后,将变量声明为 const 是多余的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65796556/