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

网友投稿 266 2022-09-19

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

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.

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 2double 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​​

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:云原生基础设施有哪些​
下一篇:C++核心准则CP.32:使用shared_ptr在无关线程之间共享所有权
相关文章

 发表评论

暂时没有评论,来抢沙发吧~