STL's(person) recent proposal for implicit auto&& in range based for loop made me wonder what it the proper way to iterate and modify elements of a sequence
for(auto&& elem: cont)
{
}
or
for(auto& elem: cont)
{
}
STL's(person) recent proposal for implicit auto&& in range based for loop made me wonder what it the proper way to iterate and modify elements of a sequence
for(auto&& elem: cont)
{
}
or
for(auto& elem: cont)
{
}
Both are equivalent; in the first case, "reference collapsing" means that the type of elem
becomes an lvalue reference since its initialiser is an lvalue. I'd say the second is more "proper" since it expresses what's actually happening.
(Unless, as pointed out in the duplicate's answer, the container breaks the container requirements as std::vector<bool>
does, with a reference
type that isn't actually a reference type. In that case, the first will bind elem
to a temporary of that type, while the second won't compile.)
There is no such thing as "proper"; it depends on what you're iterating over and what you want to do with each iteree.