C++11 range-based for() loops evaluate once or multiple times?(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() 循环评估一次还是多次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++11 基于范围的 for() 循环评估一次还是多次?


- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07