简体   繁体   中英

returning a move-only rvalue reference

In the following code:

#include <memory>

struct C {
    C() = default;
    C(C const&) = delete;
    C(C&&) = default;

    int a;
};

C foo(C&& c) {
    return c;
}

int main()
{
  auto c = foo(C{});
}

I get an error at the return statement of foo :

Use of deleted function 'C::C(const C&)'". 

Why is trying to call the copy constructor? Shouldn't it be using the move constructor since c is an rvalue reference? And even if not for that reason, shouldn't a return statement always call the move constructor since the value can no linger be used after the return ?

Inside function foo , c , a named thing, is an lvalue. To invoke the move constructor, you'd need to explicitly make it look like an rvalue

return std::move(c);

As pointed out by juanchopanza c is an lvalue (since it has a name) so it will try to copy that. instead of having to call std::move in the return statement though you can leverage the fact the local objects and function parameters that were passed by value can be considered as rvalues in the return statement. That lets you rewrite the function like

C foo(C c) {
    return c;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM