why child class can convert lvalue to rvalue? in c++ perfect forwarding

  c++
using namespace std;

class Data {
public:
    Data() {}
    ~Data() {}

    Data(const Data& t) { cout << "Copy Constructor" << endl; }
    Data(Data&& t) noexcept { cout << "Move Constructor" << endl; }
    Data& operator=(const Data& t) {
        cout << "Copy =" << endl;
        return *this;
    }
    Data& operator=(Data&& t) noexcept {
        cout << "Move =" << endl;
        return *this;
    }
};

class Data2 : public Data {};

class Test {
public:
    void setData(std::shared_ptr<Data>&& d) { data = std::forward<std::shared_ptr<Data>>(d); }

private:
    std::shared_ptr<Data> data;
};

int main() {
    Test t;
    auto d = std::make_shared<Data>();
    t.setData(d); // error
    t.setData(move(d)); // ok

    auto d1 = std::make_shared<Data2>();
    t.setData(d1); // why ok????????????

    int debug = 0;
}

Why doesn’t t.setData(d1) require std::move to convert d1 to an rvalue but t.setData(d) doesn’t compile?

Source: Windows Questions C++

LEAVE A COMMENT