Why is move constructor for unique_ptr not being called when its a member variable? [duplicate]

1 day ago 2
ARTICLE AD BOX

Why b(rhs.b) doesn't call bar(bar&&) ?

Because rhs.b is an lvalue, and rvalue references don't bind to lvalues. As a result – and because lvalue references do bind to lvaluesthe overload bar(const bar&), i.e., the copy constructor, is selected instead of bar(bar&&).

In order to get the move constructor selected, you need to mark rhs.b as "available for moving" with (<utility>) std::move() when initializing foo's b member:

foo(foo&& rhs): b(std::move(rhs.b)) { /* ... */ } ^^^^^^^^^

This is a cast that turns the expression rhs.b into an xvalue, i.e., an rvalue, which binds to an rvalue reference. So, the move constructor is selected this time.

But if I use the default move constructor, then b is moved.

The default move constructor performs a member-wise move.

answered Oct 14, 2020 at 7:17

jfMR's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article