x [0] ==当x是const int []时,C ++ 11中的1个常量表达式? [英] x[0] == 1 constant expression in C++11 when x is const int[]?

查看:78
本文介绍了x [0] ==当x是const int []时,C ++ 11中的1个常量表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is the following C++11 program ill-formed?

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

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

int main() {}

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

gcc and clang seem to think so, but why isn't x[0] == 1 a constant expression?

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:




一个非易失性glvalue(是,x [0]是整数(是,它具有const int类型)或枚举类型的glvalue和非易失性,该枚举类型是指通过先前的初始化(是yes初始化)的非易失性const对象(是,它具有const int类型) 1),用常量表达式初始化(​​是1是常量表达式)

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)

似乎是真的,<$ c的第一个元素$ c> x 数组满足这些条件。

Seems true, the first element of the x array satisfies these conditions.

1 == 1

是这是编译器错误,标准缺陷还是我缺少什么?

Is this a compiler bug, standard defect, or am i missing something?

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

What part of 5.19 [expr.const] says this isn't a constant expression?

推荐答案

在5.19中:


A [。 ..]表达式是一个常量表达式,除非它涉及以下[...]之一:

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


  • 左值-rvalue转换(4.1),除非将其应用于

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


  • 整数或枚举类型的glvalue,该值引用具有以下内容的非易失性const对象:先前的初始化,使用常量表达式进行初始化,或者

  • 文字类型的glvalue引用用constexpr定义的非易失性对象,或者将
    引用到子表达式-这样的对象的对象,或者

  • 文字类型的glvalue,它是指用常量
    表达式初始化的非易失性临时对象

插入简而言之,如果满足以下条件,则只能在常量表达式中进行左值到右值转换:

Putting it plainly, lvalue-to-rvalue conversion can only be done in constant expressions if:


  • 已初始化的常量积分(或枚举)声明带有常量: const int x = 3;

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

  • 使用常量表达式初始化的临时对象...

  • a constant integral (or enum) declaration initialized with a constant: const int x = 3;.
  • a declaration with constexpr: constexpr int x[] = {1,2,3};.
  • a temporary object initialized with a constant expression...

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

Your example does include lvalue-to-rvalue conversion, but has none of these exceptions, so x is not a constant expression. If, however, you change it to:

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

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

int main() {}

然后一切都很好。

这篇关于x [0] ==当x是const int []时,C ++ 11中的1个常量表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆