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

共 1701字,需浏览 4分钟

 ·

2020-04-20 23:21

0c8e22b5d51ecef0dbb980a1453a9c4e.webp

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(反面示例)
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)是为引入多个变量而特别设计的。

auto [iter, inserted] = m.insert_or_assign(k, val);
if (inserted) { /* new entry was inserted */ }
Example(示例)
template 
bool any_of(InputIterator first, InputIterator last, Predicate pred);

or better using concepts:

更好的选择是使用concepts:

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

or(或者):

double scalbn(    // better: x * pow(FLT_RADIX, n); FLT_RADIX is usually 2
double x, // base value
int n // exponent
);

or(又或者):

// better: base * pow(FLT_RADIX, exponent); FLT_RADIX is usually 2
double scalbn(double base, int exponent);
Example(示例)
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




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!


浏览 18
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报