Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning a move-only rvalue reference

Tags:

c++

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?

like image 772
Baruch Avatar asked Jun 17 '26 16:06

Baruch


1 Answers

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);
like image 151
juanchopanza Avatar answered Jun 20 '26 07:06

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!