1

I just watched Scott Meyers Universal References in C++11 and there was one thing I could not quite understand.

I am a bit confused as to what the difference is between a auto as a "universal reference", i.e. auto&& and a regular auto, when do they differ?

Foo f;
Foo& lvr = f;

auto lvr_a = f; // Foo&
auto rvr_a = std::move(f); // Foo&& or is it Foo?

auto&& lvr_b = f; // Foo& && => Foo&
auto&& lvr_b = std::move(f); // Foo&& && => Foo&&
ildjarn
  • 62,044
  • 9
  • 127
  • 211
ronag
  • 49,529
  • 25
  • 126
  • 221

1 Answers1

2

auto will decay to the value type (ie take a copy with copy constructor), whereas auto&& will preserve the reference type.

See here: C++11: Standard ref for action of `auto` on const and reference types

auto rvr_a = std::move(f); // Foo&& or is it Foo?

It's just Foo. So this is the same as:

Foo rvr_a = std::move(f); // Foo&& or is it Foo?

But note this will still call move constructor if there is one.

Community
  • 1
  • 1
Andrew Tomazos
  • 66,139
  • 40
  • 186
  • 319