C++核心準則ES.31:不要用宏定義常量或函數

ES.31: Don't use macros for constants or "functions"

ES.31:不要用宏定義常量或函數

 

Reason(原因)

Macros are a major source of bugs. Macros don't obey the usual scope and type rules. Macros don't obey the usual rules for argument passing. Macros ensure that the human reader sees something different from what the compiler sees. Macros complicate tool building.

宏是錯誤的主要來源之一。宏不會遵守通常的範圍和類型準則。宏也不會遵守參數傳遞準則。宏爲人提供一個和編譯器視角有些不同的視角。宏讓工具構建變得更復雜。

 

Example, bad(反面示例)

  •  
  •  
#define PI 3.14#define SQUARE(a, b) (a * b)

Even if we hadn't left a well-known bug in SQUARE there are much better behaved alternatives; for example:

雖然SQUARE定義中不存在已知的錯誤,但確實存在可以動作更好的其他選項。


 
constexpr double pi = 3.14;
template<typename T> T square(T a, T b) { return a * b; }

 

Enforcement(實施建議)

Scream when you see a macro that isn't just used for source control (e.g., #ifdef)

當給你看到宏定義不是用於代碼控制(例如#ifdef)時,一定要尖叫。

 

原文鏈接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es31-dont-use-macros-for-constants-or-functions

 


 

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

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

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