C++11 基于范围的 for() 循环评估一次还是多次?

2021-12-26 00:00:00 for-loop foreach c++ c++11

鉴于此 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.

相关文章