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

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

问题描述

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答案

不,不是.

= 的右侧,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.5 "Initializers" 中没有任何内容明确使这成为可能,其余部分由其他地方的规则填充.

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 用它自己的 (indeterminate) 值初始化.——结束示例 ]

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天全站免登陆