在将 constexpr 添加到语言后,将变量声明为 const 是否多余?

Is declaring variables as const redundant after constexpr was added to the language?

由于关键字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.

例如:你不能声明barconstexpr

int foo;

std::cin >> foo;

constexpr int bar = foo;  // compilation error

但你可以声明它const

int foo;

std::cin >> foo;

const int bar = foo;  // compile

添加到@max66的回答:constexpr只能替换一个顶级 const。它永远不能替代指向 const 或 const 引用的指针。因此,有时 constexprconst 可以在同一个声明中使用。例如

const char* const s = "Hello";

可以替换为:

constexpr const char* s = "Hello";

不,一点也不。

constexpr 表示“常量表达式”,如 [可能] 静态已知,如“[可能] 在编译时已知”。

const表示“初始化后不可更改”。

这些是完全不同的概念。例如,const 对象可以使用运行时值进行初始化。

constexpr可以隐含const,但const肯定不隐含constexpr.

(我认为 constexpr 是一个非常混乱的名字,因此。)