Does a C++11 range-based for loop condition get evaluated every cycle?

C++PerformanceFor LoopC++11Foreach

C++ Problem Overview


for(auto& entity : memoryManager.getItems()) entity->update(mFrameTime);

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

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

(memoryManager.getItems() returns a std::vector<Entity*>&)

C++ Solutions


Solution 1 - C++

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
    }
}

where range-init is the expression (surrounded by parentheses) or braced-init-list after the :

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVittorio RomeoView Question on Stackoverflow
Solution 1 - C++Mike SeymourView Answer on Stackoverflow