1

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)
{
}
NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277
  • or of [Proper style for declaration in range-based for](http://stackoverflow.com/questions/9994789/proper-style-for-declaration-in-range-based-for) – MatthiasB Feb 14 '14 at 14:32
  • A rvalue reference is a normal reference _which can also bind to a temporary_. Do you see a temporary? – Damon Feb 14 '14 at 14:39

2 Answers2

1

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.)

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • http://stackoverflow.com/a/13130795/700825 – NoSenseEtAl Feb 14 '14 at 14:42
  • @NoSenseEtAl: Fair enough, I didn't consider non-conformant containers like `std::vector`. – Mike Seymour Feb 14 '14 at 14:46
  • regarding vector http://blogs.msdn.com/b/vcblog/archive/2013/06/28/c-11-14-stl-features-fixes-and-breaking-changes-in-vs-2013.aspx and technically vector is not a container, though im sure you know that... http://www.gotw.ca/gotw/050.htm – NoSenseEtAl Feb 14 '14 at 15:09
0

There is no such thing as "proper"; it depends on what you're iterating over and what you want to do with each iteree.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055