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

 


 

觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

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