Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 range-based for loop on temp object [duplicate]

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*>&)

like image 620
Vittorio Romeo Avatar asked Apr 02 '13 13:04

Vittorio Romeo


People also ask

What is a ranged based for loop?

Remarks. Use the range-based for statement to construct loops that must execute through a range, which is defined as anything that you can iterate through—for example, std::vector , or any other C++ Standard Library sequence whose range is defined by a begin() and end() .

Are range-based for loops faster?

Range-for is as fast as possible since it caches the end iterator[citation provided], uses pre-increment and only dereferences the iterator once. Then, yes, range-for may be slightly faster, since it's also easier to write there's no reason not to use it (when appropriate).

How does range-based for loop work in C++?

Range-based for loop in C++ Range-based for loop in C++ is added since C++ 11. It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.

What is Auto in C++ for loop?

Range-based for loop in C++ Often the auto keyword is used to automatically identify the type of elements in range-expression. range-expression − any expression used to represent a sequence of elements. Also Sequence of elements in braces can be used.


1 Answers

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 :

like image 84
Mike Seymour Avatar answered Oct 11 '22 20:10

Mike Seymour