gpt4 book ai didi

c++ - 当 x 为 const int[] 时,x[0] == 1 C++11 中的常量表达式?

转载 作者:IT老高 更新时间:2023-10-28 21:53:06 24 4
gpt4 key购买 nike

以下 C++11 程序是否格式错误?

const int x[] = {1,2,3};

static_assert(x[0] == 1, "yay");

int main() {}

gcc 和 clang 似乎都这么认为,但是为什么 x[0] == 1 不是一个常量表达式呢?

x[0] == 1
subscript operator
*(x+0) == 1
array-to-pointer conversion (int* p = x)
*(p+0) == 1
pointer addition
*p == 1
indirection (lvalue y = x[0])
y == 1
lvalue-to-rvalue conversion:

a non-volatile glvalue (yes, x[0] is a glvalue and non-volatile) of integral (yes it has type const int) or enumeration type that refers to a non-volatile const object (yes it has type const int) with a preceding initialization (yes initialized with 1), initialized with a constant expression (yes 1 is constant expression)

看起来不错,x 数组的第一个元素满足这些条件。

1 == 1

?

这是编译器错误、标准缺陷还是我遗漏了什么?

5.19 [expr.const] 的哪一部分说这不是一个常量表达式?

最佳答案

在 5.19 中:

A [...]expression is a constant expression unless it involves one of the following [...]:

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

    • a glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression, or
    • a glvalue of literal type that refers to a non-volatile object defined with constexpr, or that refers to a sub-object of such an object, or
    • a glvalue of literal type that refers to a non-volatile temporary object initialized with a constant expression

说白了,左值到右值的转换只能在常量表达式中进行,如果:

  • 用常量初始化的常量整数(或枚举)声明:const int x = 3;.
  • 带有 constexpr 的声明:constexpr int x[] = {1,2,3};.
  • 使用常量表达式初始化的临时对象...

您的示例确实包括左值到右值的转换,但没有这些异常,因此 x 不是常量表达式。但是,如果您将其更改为:

constexpr int x[] = {1,2,3};

static_assert(x[0] == 1, "yay");

int main() {}

那么一切都很好。

关于c++ - 当 x 为 const int[] 时,x[0] == 1 C++11 中的常量表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18903113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com