C++核心准则ES.71: 如果可以,使用范围for代替普通的for语句
发布日期:2021-07-01 05:28:23 浏览次数:2 分类:技术文章

本文共 2261 字,大约阅读时间需要 7 分钟。

ES.71: Prefer a range-for-statement to a for-statement when there is a choice

ES.71: 如果可以,使用范围for语句代替普通的for语句。

 

Reason(原因)

Readability. Error prevention. Efficiency.

可读性,防错和效率。

 

Example(示例)

for (gsl::index i = 0; i < v.size(); ++i)   // bad        cout << v[i] << '\n';for (auto p = v.begin(); p != v.end(); ++p)   // bad    cout << *p << '\n';for (auto& x : v)    // OK    cout << x << '\n';for (gsl::index i = 1; i < v.size(); ++i) // touches two elements: can't be a range-for    cout << v[i] + v[i - 1] << '\n';for (gsl::index i = 0; i < v.size(); ++i) // possible side effect: can't be a range-for    cout << f(v, &v[i]) << '\n';for (gsl::index i = 0; i < v.size(); ++i) { // body messes with loop variable: can't be a range-for    if (i % 2 == 0)        continue;   // skip even elements    else        cout << v[i] << '\n';}

A human or a good static analyzer may determine that there really isn't a side effect on v in f(v, &v[i]) so that the loop can be rewritten.

"Messing with the loop variable" in the body of a loop is typically best avoided.

程序员或者好的静态分析软件或许可以判断f(v,&v[i])中的v实际上并不存在副作用,因此该循环可以被重写。通常情况下,最好避免在循环体中“乱用循环变量”。

 

Note(注意)

Don't use expensive copies of the loop variable of a range-for loop:

不要在循环体中进行代价高昂的循环变量拷贝。

for (string s : vs) // ...

This will copy each elements of vs into s. Better:

这会导致vs的每个元素都被拷贝。较好的做法是:

for (string& s : vs) // ...

Better still, if the loop variable isn't modified or copied:

如果循环变量不会被修改或拷贝,下面的做法更好。

for (const string& s : vs) // ...

 

Enforcement(实施建议)

Look at loops, if a traditional loop just looks at each element of a sequence, and there are no side effects on what it does with the elements, rewrite the loop to a ranged-for loop.

检查循环代码,如果一个传统的循环只是按照顺序读取每个元素,而且对元素的操作不存在副作用,使用范围for语句重写循环代码。

 

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es71-prefer-a-range-for-statement-to-a-for-statement-when-there-is-a-choice

 


 

新书介绍

以下是本人3月份出版的新书,拜托多多关注!

 

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。

 

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

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

转载地址:https://oothinking.blog.csdn.net/article/details/107514570 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:C++核心准则ES.72:如果存在明显的循环变量,for语句要好于while语句
下一篇:C++核心准则ES.70:进行选择时,switch语句比if语句好

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年05月07日 07时42分27秒