是否每个循环都评估基于 C++11 范围的 for 循环条件?

2021-12-11 00:00:00 performance for-loop foreach c++ c++11
for(auto& entity : memoryManager.getItems()) entity->update(mFrameTime);

如果 memoryManager 包含 1000 个项目,在循环开始时 memoryManager.getItems() 会被调用 1000 次还是只调用一次?

If memoryManager contains 1000 items, does memoryManager.getItems() get called 1000 times or only one at the beginning of the loop?

编译器是否使用 -O2(或 -O3)运行任何优化?

Does the compiler run any optimization with -O2 (or -O3)?

(memoryManager.getItems() 返回一个 std::vector&)

推荐答案

它只评估一次.该标准将基于范围的 for 语句定义为等效于:

It is only evaluated once. The standard defines a range-based for statement as equivalent to:

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

其中 range-init 之后的表达式(用括号括起来)或花括号初始化列表:

相关文章