Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

c++ - 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)?
};

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

Quotes from the Standard would be highly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

C++03/C++11 answer


No, it's not.

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

  • 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.

  • 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.

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]: 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; }

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

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]: [..] [ Note: Operations involving indeterminate values may cause undefined behavior. —end note ]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...