首页 文章详情

C++核心准则ES.43: 避免在表达式中使用无定义的运算次序

面向对象思考 | 508 2020-05-10 23:21 0 0 0
UniSMS (合一短信)

f4de2c2c2de847c2fc60369a4e96e68c.webp

ES.43: Avoid expressions with undefined order of evaluation

ES.43: 避免在表达式中使用无定义的运算次序


Reason(原因)

You have no idea what such code does. Portability. Even if it does something sensible for you, it may do something different on another compiler (e.g., the next release of your compiler) or with a different optimizer setting.

你无法知道这样的代码会做什么。可移植性。虽然可以带来某些实际的好处,但可能只要换一个编译器(例如编译器的下一个版本)或者修改了优化设定情况就会发生变化。


Note(注意)

C++17 tightens up the rules for the order of evaluation: left-to-right except right-to-left in assignments, and the order of evaluation of function arguments is unspecified.

C++17收紧了有关运算顺序的规则:除了从右向左的赋值之外都是从左向右计算,函数参数的求值次序是无定义的。

However, remember that your code may be compiled with a pre-C++17 compiler (e.g., through cut-and-paste) so don't be too clever.

但是,还是不要忘了,你的代码可能被C++17之前的编译器编译(例如通过剪切和粘贴),不要过于聪明。


Example(示例)

v[i] = ++i;   //  the result is undefined

A good rule of thumb is that you should not read a value twice in an expression where you write to it.

一条非常好的经验规则是:不要在一个需要对其写入的表达式中两次读取变量的值。


Enforcement(实施建议)

Can be detected by a good analyzer.

这个问题可以被良好的代码分析器检出。


原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es43-avoid-expressions-with-undefined-order-of-evaluation




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

45aef5af36be273f6abed181b9c054d9.webp


good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter