Daniel Anderson
Daniel Anderson

Reputation: 139

Should I use auto&& x instead of auto& x?

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

Answers (1)

Drew Dormann
Drew Dormann

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.

  • Use auto&& if you want your code to always compile.
  • Use 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

Related Questions