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)?
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. e.g.
class Child: public Parent {
public:
Child(Initialisee&& i): Parent(std::move(i)) { }
};