*&++++ i是否会在C ++ 03中导致未定义的行为? [英] Does *&++i cause undefined behaviour in C++03?
问题描述
在另一个答案中指出,在C ++ 11之前,其中i
是int
,然后使用表达式:
In another answer it was stated that prior to C++11, where i
is an int
, then use of the expression:
*&++i
引起不确定的行为.这是真的吗?
caused undefined behaviour. Is this true?
在另一个答案上,在评论中进行了一些讨论,但似乎没有说服力.
On the other answer there was a little discussion in comments but it seems unconvincing.
推荐答案
询问*&++i
本身是否具有UB毫无意义.延迟不一定访问i
的存储值(优先级或新值),如将其用作引用的初始化表达式所见.只有涉及右值转换(在这种情况下使用)时,才有任何问题需要讨论.然后,由于我们可以使用++i
的值,因此可以使用*&++i
的值,但要与++i
完全相同.
It makes little sense to ask whether *&++i
in itself has UB. The deferencing doesn't necessarily access the stored value (prior or new) of i
, as you can see by using this as an initializer expression for a reference. Only if an rvalue conversion is involved (usage in such context) is there any question to discuss at all. And then, since we can use the value of ++i
, we can use the value of *&++i
with exactly the same caveats as for ++i
.
最初的问题本质上与i = ++i
有关,与i = *&++i
相同.在C ++ 03中,这是未定义的行为,这是因为i
在序列点之间进行了两次修改,而在C ++ 11中则是定义良好的,这是由于赋值运算符的副作用在计算值之后进行了排序左右两侧.
The original question concerned essentially i = ++i
, which is the same as i = *&++i
. That was undefined behavior in C++03, due to i
being modified twice between sequence points, and is well-defined in C++11, due to the side-effects of the assignment operator being sequenced after the value computations of the left and right hand sides.
可能需要注意的是,C ++ 98和C ++ 03标准中的非规范性示例是不正确的,将某些形式上未定义行为的情况描述为仅是未指定的行为.因此,意图一直没有完全清楚.一个好的经验法则是,不要仅仅依靠这种晦涩难懂的语言案例,而避免它们:避免为了理解代码而不必成为语言律师.
It is perhaps relevant to note that the non-normative examples in the C++98 and C++03 standards, were incorrect, describing some cases of formally Undefined Behavior as merely unspecified behavior. Thus, the intent has not been entirely clear, all the way back. A good rule of thumb is to simply not rely on such obscure corner cases of the language, to avoid them: one should not need to be a language lawyer in order to make sense of the code…
这篇关于*&++++ i是否会在C ++ 03中导致未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!