A range-based for
statement is defined in §6.5.4 to be equivalent to:
{
auto && __range = range-init;
for ( auto __begin =
Wouldn't auto& suffice?
No, it wouldn't. It wouldn't allow the use of an r-value expression that computes a range. auto&&
is used because it can bind to an l-value expression or an r-value expression. So you don't need to stick the range into a variable to make it work.
Or, to put it another way, this wouldn't be possible:
for(const auto &v : std::vector{1, 43, 5, 2, 4})
{
}
Wouldn't
const auto&
suffice?
No, it wouldn't. A const std::vector
will only ever return const_iterator
s to its contents. If you want to do a non-const
traversal over the contents, that won't help.