C++11 基于范围的 for() 循环评估一次还是多次? [英] C++11 range-based for() loops evaluate once or multiple times?

查看:25
本文介绍了C++11 基于范围的 for() 循环评估一次还是多次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此 C++11 示例代码:

Given this C++11 example code:

for ( const auto &foo : bar() )
{
    // ... do something with foo...
}

这个例子中的表达式bar()是否被标准保证只计算一次?

Is it guaranteed by the standard that the expression bar() in this example is evaluated only once?

或者它最终会在循环的每次迭代中被调用吗?

Or could it end up being called at every iteration of the loop?

推荐答案

它只被评估一次.标准说基于范围的 for 循环相当于这样:

It is evaluated only once. The standard says that the range-based for loop is equivalent to this:

§6.5.4 基于范围的 for 语句 [stmt.ranged]

§6.5.4 The range-based for statement [stmt.ranged]

{
  auto && __range = range-init;
  for ( auto __begin = begin-expr,
        __end = end-expr;
        __begin != __end;
        ++__begin ) {
    for-range-declaration = *__begin;
    statement
  }
}

with range-init 在您的情况下等效于 ( bar() ) (您指定的表达式,用括号括起来).如您所见,该表达式仅计算一次.

with range-init being equivalent to ( bar() ) in your case (the expression you specify, surrounded by parenthesis). That expression is only evaluated once as you can see.

这篇关于C++11 基于范围的 for() 循环评估一次还是多次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆