简体   繁体   中英

Convince a constructor to move an object a parent's constructor

I've been attempting to forward an object to a parent without having the object copied. I cannot seem to be able to do this, and don't know why.

Here is an example of the kind of thing I would like to do. It does not compile, however.

class Initialisee {
    public:
        Initialisee() = default;
        Initialisee(const Initialisee&) = delete;
        Initialisee(Initialisee&&) = default;
};

class Parent {
    public:
        Parent(const Initialisee i) { }
};

class Child: public Parent {
    public:
        Child(const Initialisee i): Parent(std::move(i)) { }
};

This won't compile as, despite the std::move() , the child is still trying to copy-construct the object to pass it to the parent's constructor. I'm using MSVC 2019 (16.10.3) with the latest language features enabled.

Why won't it let me do this? Is this a bug or a quirk in the language? How could I write this in the correct way without having to implement a copy constructor on the object (which would be very expensive for the situations I actually want to do this for)?

You cannot move out of const objects. It should be Child(Initialisee i) , not Child(const Initialisee i) .

I have encountered something similar myself.

Move operation is supposed to perform modification on the object to be moved from; but i is marked as const and can't be moved from. Especially, const Initialisee can't be bound to Initialisee&& , then it can't be passed to move constructor of Initialisee .

If your intent is to perform move operation it's better to declare it as rvalue-reference. eg

class Child: public Parent {
    public:
        Child(Initialisee&& i): Parent(std::move(i)) { }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM