dimanche 26 février 2017

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

#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; in other words, 1 is enough.

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

Aucun commentaire:

Enregistrer un commentaire