C++核心準則ES.43: 避免在表達式中使用無定義的運算次序

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

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章