数组初始化,是否引用前一个元素? [英] array initialization, is referencing a previous element ok?

查看:49
本文介绍了数组初始化,是否引用前一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const QPointF points[] =
{
    QPointF(r.left() - i, r.top() - i),
    QPointF(r.right() + i, r.top() - i),
    QPointF(r.right() + i, r.bottom() + i),
    QPointF(r.left() - i, r.bottom() + i),
    points[0] // is this line valid (according to the C++ standard)?
};

虽然使用 MS Visual Studio 编译器进行编译,但根据 C++ 标准,我不确定这是否是有效代码.

While this compiles with the MS Visual Studio Compiler, i am not sure if this is valid code according to the C++ Standard.

引用标准将高度赞赏.

推荐答案

C++03/C++11 answer

不,不是.

= 的右侧,points 确实存在1 但初始化器仅在其所有操作数都已被应用评价.

On the right-hand side of the =, points does exist1 but the initialiser is only applied after all its operands have been evaluated.

  • 如果 points 在命名空间范围内(因此具有静态存储持续时间并且已被零初始化2),那么这是安全的",但您的使用 points[0] 将会给你 0,而不是 QPointF(r.left() - i, r.top() - i) 再次.

  • If points is at namespace scope (and thus has static storage duration and has been zero-initialized2), then this is "safe" but your use of points[0] there is going to give you 0, rather than QPointF(r.left() - i, r.top() - i) again.

如果 points 有自动存储时间 —它尚未初始化,因此您对 points[0] 的使用试图使用未初始化的变量,其中 points[0] 具有不确定的值......这是坏3.

If points has automatic storage duration — it has not yet been initialised so your use of points[0] is attempting to use an uninitialised variable, where points[0] has an indeterminate value... which is bad3.

很难为此提供标准参考,只能说8.5Initializers"中没有任何内容明确地使这成为可能,其他地方的规则填补了其余部分.

It's difficult to provide standard references for this, other than to say that there is nothing in 8.5 "Initializers" that explicitly makes this possible, and rules elsewhere fill in the rest.

1 [n3290: 3.3.2/1]: 名称的声明点紧跟在其完整的声明符之后(条款8) 以及在其初始化程序(如果有)之前,除非以下说明.[ 示例:

1 [n3290: 3.3.2/1]: The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any), except as noted below. [ Example:

int x = 12;
{ int x = x; }

这里第二个 x 用它自己的 (不确定) 值初始化.——结束示例 ]

Here the second x is initialized with its own (indeterminate) value. —end example ]

2 [n3290: 3.6.2/2]: 静态存储持续时间(3.7.1)或线程存储持续时间(3.7.2)的变量应为零-初始化(8.5)在任何其他初始化发生之前.[..]

2 [n3290: 3.6.2/2]: Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place. [..]

3 [n3290: 17.6.3.3/2]: [..] [ 注意: 操作涉及不确定的值可能会导致未定义的行为.—结束注释 ]

3 [n3290: 17.6.3.3/2]: [..] [ Note: Operations involving indeterminate values may cause undefined behavior. —end note ]

这篇关于数组初始化,是否引用前一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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