2
#include <vector>

using namespace std;

int main
{
    vector<int> coll;
    for (auto&  i : coll) {} // 1
    for (auto&& i : coll) {} // 2
}

According to cppref:

It is safe, and in fact, preferable in generic code, to use deduction to forwarding reference, for (auto&& var : sequence).

However, I think 2 is completely equivalent to 1; because i is still an lvalue even it is declared as auto&&.

Why is it recommended to use auto&& rather than auto& in range-for loop?

xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • 2
    try with `std::vector`... – Jarod42 Feb 26 '17 at 16:14
  • Let's consider `std::vector`, why is `auto&&` ok and `auto&` not ok? – xmllmx Feb 26 '17 at 16:25
  • The duplicate Q&A has an answer to that question. – Emil Laine Feb 26 '17 at 16:29
  • @tuple_cat, no. That Q&A doesn't explain: why is `auto&&` ok and `auto&` not ok? – xmllmx Feb 26 '17 at 16:31
  • 2
    It is there, hidden below the "The special case of proxy iterators" heading. – Emil Laine Feb 26 '17 at 16:33
  • I've examined the section you pointed out, but I'm still not clear: why is `auto&&` ok and `auto&` not ok? – xmllmx Feb 26 '17 at 16:35
  • Because `vector` doesn't return a real reference to a bool but a "fake" one that is hidden behind a [proxy class](http://en.cppreference.com/w/cpp/container/vector_bool/reference). – zett42 Feb 26 '17 at 16:37
  • @zett42, I know why `auto&` is not ok; but I don't know why `auto&&` is ok in such a case. – xmllmx Feb 26 '17 at 16:39
  • 3
    @xmllmx because this is how c++ works. rvalue don't bind to lvalue reference, but rvalue can bind to rvalue references. More precisely, `auto&&` act as a forwarding reference, so lvalue can be bound too. If you have any questions about this, research and ask another question. – Guillaume Racicot Feb 26 '17 at 16:49
  • @GuillaumeRacicot, thanks, i'm clear now. – xmllmx Feb 26 '17 at 16:53
  • 1
    If `auto&` would actually work, you would have a dangling reference, because the lvalue's lifetime ends when the body of the for loop is entered. As I see it, `auto&&` basically prolongs the lifetime of the lvalue to the body of the loop. – zett42 Feb 26 '17 at 17:00

0 Answers0