前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.31:不要用宏定义常量或函数​

C++核心准则ES.31:不要用宏定义常量或函数​

作者头像
面向对象思考
发布2020-05-20 00:17:41
2810
发布2020-05-20 00:17:41
举报

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(反面示例)

代码语言:javascript
复制
#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定义中不存在已知的错误,但确实存在可以动作更好的其他选项。

代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-05-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ES.31: Don't use macros for constants or "functions"
  • Reason(原因)
    • Enforcement(实施建议)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档