I learned this trick from Stephan Lavavej’s proposal for ISO C++.
Using auto for range-based for loops is inefficient. It will copy each
element out of the container.
1
| |
Using auto& is efficient, and works with both const and non-const containers.
1
| |
Alas, it does not work with iterators that return proxy objects, such as the
infamous std::vector<bool>. You cannot bind a temporary object to a non-const reference.
The trick is to use auto&&. It works with both const and non-const containers,
but also works with proxy objects. It is always correct and efficient!
1
| |