前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则​ES.71: 如果可以,使用范围for代替普通的for语句

C++核心准则​ES.71: 如果可以,使用范围for代替普通的for语句

作者头像
面向对象思考
发布2020-06-03 11:03:02
4830
发布2020-06-03 11:03:02
举报
文章被收录于专栏:C++核心准则原文翻译

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

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

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

代码语言:javascript
复制
for (string s : vs) // ...

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

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

代码语言:javascript
复制
for (string& s : vs) // ...

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

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

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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ES.71: Prefer a range-for-statement to a for-statement when there is a choice
  • Reason(原因)
    • Enforcement(实施建议)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档