mercredi 14 octobre 2020

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);

Aucun commentaire:

Enregistrer un commentaire