前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.10:每次只定义一个名称

C++核心准则ES.10:每次只定义一个名称

作者头像
面向对象思考
发布2020-04-22 11:34:04
2260
发布2020-04-22 11:34:04
举报

ES.10: Declare one name (only) per declaration

ES.10:每次只定义一个名称

Reason(原因)

One declaration per line increases readability and avoids mistakes related to the C/C++ grammar. It also leaves room for a more descriptive end-of-line comment.

每行一个声明的做法可以提高可读性,避免C/C++语法相关的错误。也可以为描写性行末注释留出空间。

Example, bad(反面示例)
代码语言:javascript
复制
char *p, c, a[7], *pp[7], **aa[10];   // yuck!Exception

A function declaration can contain several function argument declarations.

函数声明可以包含多个参数声明。

Exception(例外)

A structured binding (C++17) is specifically designed to introduce several variables:

结构化绑定(C++17)是为引入多个变量而特别设计的。

代码语言:javascript
复制
auto [iter, inserted] = m.insert_or_assign(k, val);
if (inserted) { /* new entry was inserted */ }
Example(示例)
代码语言:javascript
复制
template <class InputIterator, class Predicate>
bool any_of(InputIterator first, InputIterator last, Predicate pred);

or better using concepts:

更好的选择是使用concepts:

代码语言:javascript
复制
bool any_of(InputIterator first, InputIterator last, Predicate pred);
Example(示例)
代码语言:javascript
复制
double scalbn(double x, int n);   // OK: x * pow(FLT_RADIX, n); FLT_RADIX is usually 2

or(或者):

代码语言:javascript
复制
double scalbn(    // better: x * pow(FLT_RADIX, n); FLT_RADIX is usually 2
    double x,     // base value
    int n         // exponent
);

or(又或者):

代码语言:javascript
复制
// better: base * pow(FLT_RADIX, exponent); FLT_RADIX is usually 2
double scalbn(double base, int exponent);
Example(示例)
代码语言:javascript
复制
int a = 7, b = 9, c, d = 10, e = 3;

In a long list of declarators it is easy to overlook an uninitialized variable.

如果是一长串声明,很容易漏掉某个没有初始化的变量。

Enforcement(实施建议)

Flag variable and constant declarations with multiple declarators (e.g., int* p, q;)

标记包含多个变量和常数的声明语句。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es10-declare-one-name-only-per-declaration

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ES.10: Declare one name (only) per declaration
    • Reason(原因)
      • Example, bad(反面示例)
        • Exception(例外)
          • Example(示例)
            • Example(示例)
              • Example(示例)
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档