Search code examples
c++c++11rvalue-referencetype-deduction

Automatic type deduction and auto&& vs auto


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&&

Solution

  • 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.