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

ES.31: Don't use macros for constants or "functions"
ES.31:不要用宏定義常量或函數(shù)
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.
宏是錯誤的主要來源之一。宏不會遵守通常的范圍和類型準則。宏也不會遵守參數(shù)傳遞準則。宏為人提供一個和編譯器視角有些不同的視角。宏讓工具構建變得更復雜。
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 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
覺得本文有幫助?請分享給更多人。
關注微信公眾號【面向對象思考】輕松學習每一天!
面向對象開發(fā),面向對象思考!
