c++ - 在将 constexpr 添加到语言后,将变量声明为 const 是多余的吗?

标签 c++ c++11 constants constexpr

作为关键字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 as constexpr?


并且必须在编译时计算(忽略 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/

相关文章:

c++ - clang-format noop .clang-格式文件

c# - 在 C# 中命名 Windows API 常量

c - 无法写入 int const 数组

C++ 和 QT4.5 - 传递一个 const int& 矫枉过正?通过引用传递对信号/插槽有帮助吗?

c++ - 使用重载构造函数时出现类型不完整错误

c++ - 内存堆损坏 + GFlags 工具但不是结果

c++ - 如何消除 'The last statement should return a value' 警告?

c++ - 如何确定传入连接是否需要 SSL?

c++ - 具有任何返回类型的函数模板参数

c++ - 禁用 Eclipse 的错误发现。 (科丹误报)