Reputation: 139
I often find myself doing:
for(auto& v : cont) {...}
or
auto &r = GetValue();
Now someone at work suggested we do:
for(auto&& v : cont) {...}
and
auto&& r = GetValue();
I wonder if there is an advantage of doing one over the other ?
Upvotes: 5
Views: 236
Reputation: 63775
I wonder if there is an advantage of doing one over the other ?
They are not the same.
auto& v
is an lvalue reference. Since it is not explicitly const
it can only bind to other lvalues.
auto&& v
is a forwarding reference (sometimes called a "universal reference"). It can bind to lvalues and xvalues and prvalues. All values.
auto&&
if you want your code to always compile.auto&
if, for some reason, you need to code to fail to compile when it is assigned something that is not an lvalue.Upvotes: 3