I know move semantics in c++ move constructor, but here I have some confusion:
class Derived: public Base {
std::vector<int> vec;
std::string name;
// ...
public:
// ...
// move semantics
Derived(Derived&& x) // rvalues bind here
: Base(std::move(x)),
vec(std::move(x.vec)),
name(std::move(x.name)) { }
Derived& operator=(Derived&& x) // rvalues bind here
{
Base::operator=(std::move(x));
vec = std::move(x.vec);
name = std::move(x.name);
return *this;
}
// ...
};
the move constructor Base(std::move(x)), the x have been converted to rvalue reference, how does vec(std::move(x.vec)) ?? still x existing?
The move constructor for Base
presumably has the prototype Base(Base&& b)
, so when you call Base(std::move(x))
in the constructor, the rvalue std::move(x)
, which has type Derived
, is implicitly converted to an rvalue of type Base
. The move constructor for Base
sees an rvalue reference to Base
, so it moves the members of Base
out of x
. The other members of x
have not been moved from yet, so the following move-initializations are still valid.
Move construction and move assignment don't invalidate an object. An object's invariants should still be satisfied after a move, so that its destructor will work properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With