`const int a = 1;` 是 `a` 常量表达式,如果 `a` 具有自动存储持续时间

`const int a = 1;` is `a` a constant expression, if `a` has automatic storage duration

N4527 5.20[expr.const]p2

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:

(2.7) — an lvalue-to-rvalue conversion (4.1) unless it is applied to

(2.7.1) — a non-volatile glvalue of integral or enumeration type that refers to a complete non-volatile const object with a preceding initialization, initialized with a constant expression, or

(2.7.2) — a non-volatile glvalue that refers to a subobject of a string literal (2.13.5), or

(2.7.3) — a non-volatile glvalue that refers to a non-volatile object defined with constexpr, or that refers to a non-mutable sub-object of such an object, or

(2.7.4) — a non-volatile glvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of e;

5.20[expr.const]p5

A constant expression is either a glvalue core constant expression whose value refers to an entity that is a permitted result of a constant expression (as defined below), or a prvalue core constant expression whose value is an object where, for that object and its subobjects:

— each non-static data member of reference type refers to an entity that is a permitted result of a constant expression, and

— if the object or subobject is of pointer type, it contains the address of an object with static storage duration, the address past the end of such an object (5.7), the address of a function, or a null pointer value.

An entity is a permitted result of a constant expression if it is an object with static storage duration that is either not a temporary object or is a temporary object whose value satisfies the above constraints, or it is a function.

void foo(){
    const int a = 1;//a has automatic storage duration
    int b[a]{};
}

int b[a]{};中,a是id-expression,a是左值核心常量表达式。 a是常量表达式吗?


这是对

的澄清

a 可以是纯右值核心常量表达式,但不是左值核心常量表达式,也不应该是可能的。您已经在标准中找到了措辞,所以也许最好解释一下规则为何如此。

void foo(){
    const int a = 1;//a has automatic storage duration
    static constexpr const int &ra = a;// cannot possibly be valid
}

这不可能是有效的,因为它需要在 foo 被调用之前知道 a 的地址,在 任何 a.

你的 int b[a]{}; 很好,因为它使用 a 作为纯右值核心常量表达式:它不关心 a 存储在哪里,它只关心它有什么价值.