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

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

问题描述

给定此C ++ 11示例代码:

  for(const auto& foo:bar $ b {
// ...使用foo ... do b ...
}

它是保证的标准,表达式 bar()在这个例子中只评估一次?

$ b $

解决方案

它被评估只有一次。标准说基于范围的for循环等价于:



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

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

range-init 等价于你的case中的(bar())(指定的表达式,用圆括号括起来)。该表达式只能计算一次,如您所见。


Given this C++11 example code:

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

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?

解决方案

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

§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 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天全站免登陆