问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/16259574/c11-range-based-for-loops-evaluate-once-or-multiple-times