Edmund's blog

Writing code.

Use auto&& for range-based for loops

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
for (auto elem : range)  // inefficient

Using auto& is efficient, and works with both const and non-const containers.

1
for (auto& elem : range)  // efficient

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
for (auto&& elem : range)  // efficient, and works with proxy objects