C++ is known to be a programming language that offers several options for doing stuff, and with all the options available for range-based for loops, sometimes folks (especially beginners) get confused.
My pragmatic piece of advice for C++11’s range-based for loops is:
- If you are observing the items in the container, use “const auto&”.
- If you are modifying the items in place during the iteration, use “auto&”.
That’s as simple as that!
In code:
// Observe elements for (const auto& elem : container) // Modify elements in place for (auto& elem : container)
A more detailed discussion can be found on StackOverflow (this includes also some special corner-cases, like proxy iterators as in std::vector<bool>, or auto&& in generic code):
“What is the correct way of using C++11’s range-based for?”
P.S.
I’ve also seen some code with const auto&& used in range-for, but that doesn’t seem to make sense.