array initialization, is referencing a previous element ok?(数组初始化,引用前一个元素好吗?)
问题描述
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
pointsis at namespace scope (and thus has static storage duration and has been zero-initialized2), then this is "safe" but your use ofpoints[0]there is going to give you0, rather thanQPointF(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 ]
这篇关于数组初始化,引用前一个元素好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:数组初始化,引用前一个元素好吗?
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
