开发者

What's the difference in undefined behavior between C++03 and C++11?

The new standard has different undefined behavior from the old one. The new sequencing rules, for example, mean that some arithmetic operations that use开发者_运维问答d to be undefined (for such reasons as multiple writes between sequence points) are now defined.

So, what do we need to learn anew about undefined behavior?


In my opinion the new rules are more complex to describe and to understand. For example consider that:

int x = 12;
x = x++ + 1; // undefined behaviour
x = ++x + 1; // valid

I would suggest to simply avoiding multiple side effects to the same variable in the same expression that is a rule simpler to understand. AFAIK C++0X changed some cases that were undefined behaviour in the past and that are now legal uses (for example the second of the two expressions above) but remember that there is and there will always be a difference between what is legal and what is moral ;-) ... no one is forcing you to use such things.

Actually in the above case seems that the validity of the second expression happened unintentionally as a side effect of fixing another issue (#222) in the language. The decision was to make the expression valid because it was considered that changing something from UB to well defined wasn't going to do any harm. I think however that while this didn't make any damage to programs (where of course UB is the worst possible problem), it actually made some damage to the language itself... changing a rule that was already complex to explain and understand to an even more obscure one.

IMO C++ is continuing its natural evolution from C into a language where a bunch of good-looking nice and logical statements can do wonderful things... and in which another bunch of equally good-looking, equally nice and equally logical statements can make your computer to explode instead.


C++0x changes a number of previously undefined cases to now conditionally-supported cases. The semantics is:

  • If the implementation does not support the conditionally-supported feature, it shall document that and shall emit a diagnostic for a program that violates it.
  • If the implementation does support it, it should behave to additional requirements the Standard makes on it. For example, the Standard might say something is conditionally-supported with implementation-defined semantics. If so, the implementation shall document how it supports the feature.

A popular case that previously was undefined is when passing an argument of class type having a non-trivial copy constructor, a non-trivial move contructor, or a non-trivial destructor though an ellipsis function parameter. This is now conditionally-supported, with implementation-defined semantics.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜