[dcl.constexpr] p10 sentence 3说:
In any constexpr variable declaration, the full-expression of the initialization shall be a constant expression
但是,在此声明中:
constexpr int a = 10;
constexpr int b = a;
a
不是常量表达式,因为它是泛左值核心常量表达式,但不是 permitted result of a constant expression因为它没有静态存储持续时间,并且不是临时对象。
但是,通过应用左值到右值转换,它将成为常量表达式。那么这是否意味着初始化器不需要是常量表达式,而只需转换后的最终结果即可?
最佳答案
在您引用的链接中,请参阅第 10 点:
A constant expression is either a glvalue core constant expression that refers to an entity that is a permitted result of a constant expression (as defined below), or a prvalue core constant expression whose value satisfies the following constraints:
您的问题集中在泛左值分支下的“常量表达式的允许结果”;但是在您的示例中,适用的是另一个分支“纯右值核心常量表达式”。这可以适用,因为 [conv.lval]/1,
A glvalue of a non-function, non-array type T can be converted to a prvalue
我同意,这里的“纯右值核心常量表达式”包括满足条件的左值到右值转换结果的情况,这有点令人困惑;而在标准“纯右值”的其他一些地方排除了这种情况。
关于c++ - constexpr 变量的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57391772/