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

 


 

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值