c++return-valuemove-semanticsc++17ref-qualifier

To move, or not to move from r-value ref-qualified method?


In the following C++11+ code which return statement construction should be preferred?

#include <utility>


struct Bar
{
};

struct Foo
{
    Bar bar;

    Bar get() &&
    {
        return std::move(bar); // 1
        return bar;            // 2
    }
};

Solution

  • Well, since it's a r-value ref qualified member function, this is presumably about to expire. So it makes sense to move bar out, assuming Bar actually gains something from being moved.

    Since bar is a member, and not a local object/function parameter, the usual criteria for copy elision in a return statement don't apply. It would always copy unless you explicitly std::move it.

    So my answer is to go with option number one.