Gary
Gary

Reputation: 2007

Why move constructor of member variable is not called?

Consider the following classes. If I implement the move constructor myself as follow, why bar member b is not moved but copied? But if I use the default move constructor, then b is moved. Why b(rhs.b) doesn't call bar(bar&&) ?

I use g++ 9.2.1 with --std=c++11.

class bar {
public:
    bar() { cout << "bar constructor" << endl; }
    bar(const bar& rhs) { cout << "bar copy constructor" << endl; }
    bar(bar&& rhs) { cout << "bar move constructor" << endl; }
};

class foo {
    bar b;
public:
    foo() { cout << "foo constructor" << endl; }
    foo(const foo& rhs) { cout << "foo copy constructor" << endl; }
    // foo(foo&& rhs) = default;
    foo(foo&& rhs) : b(rhs.b) { cout << "foo move constructor" << endl; } // my version
    //               ^^^^^^^^
};

foo f;
foo g = std::move(f);

Upvotes: 3

Views: 262

Answers (1)

jfMR
jfMR

Reputation: 24738

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.

Upvotes: 2

Related Questions