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

标签 c++ language-lawyer constant-expression

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表达式,a是一个左值核心常量表达式。 a 是常量表达式吗?


这是对 Is a glvalue integral constant expression a constant expression? 的澄清

最佳答案

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在哪里 被存储,它只关心它有什么值。

关于c++ - `const int a = 1;` 是 `a` 常量表达式,如果 `a` 有自动存储持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31537359/

相关文章:

C++ 编译时唯一 ID 生成器始终返回相同的值

c - 为什么 union* 和 struct* 之间会有区别?

f# - 为什么我不能把这个字符串变成文字?

c++ - const 与引用传递一起使用有什么意义? C++

c++ - 如何将 vector 内容的 vector 放入单个列 vector 中

c++ - 三元运算符中的 integral_constants

c++ - B树类实现: expression must have constant values?

c++ - constexpr 中的字节顺序

c++ - 如何 std::mutex::lock 直到函数返回

c++ - 使用 const 键从集合中删除元素