C++核心準(zhǔn)則ES.43: 避免在表達(dá)式中使用無(wú)定義的運(yùn)算次序

ES.43: Avoid expressions with undefined order of evaluation
ES.43:?避免在表達(dá)式中使用無(wú)定義的運(yùn)算次序
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.
你無(wú)法知道這樣的代碼會(huì)做什么??梢浦残浴km然可以帶來(lái)某些實(shí)際的好處,但可能只要換一個(gè)編譯器(例如編譯器的下一個(gè)版本)或者修改了優(yōu)化設(shè)定情況就會(huì)發(fā)生變化。
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收緊了有關(guān)運(yùn)算順序的規(guī)則:除了從右向左的賦值之外都是從左向右計(jì)算,函數(shù)參數(shù)的求值次序是無(wú)定義的。
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之前的編譯器編譯(例如通過(guò)剪切和粘貼),不要過(guò)于聰明。
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.
一條非常好的經(jīng)驗(yàn)規(guī)則是:不要在一個(gè)需要對(duì)其寫入的表達(dá)式中兩次讀取變量的值。
Enforcement(實(shí)施建議)
Can be detected by a good analyzer.
這個(gè)問(wèn)題可以被良好的代碼分析器檢出。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es43-avoid-expressions-with-undefined-order-of-evaluation
覺(jué)得本文有幫助?請(qǐng)分享給更多人。
關(guān)注微信公眾號(hào)【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_(kāi)發(fā),面向?qū)ο笏伎迹?/span>
