C++11 range-based for() loops evaluate once or multiple times? [duplicate]

穿精又带淫゛_ 提交于 2019-12-30 05:37:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!