Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Derived class of Move constructor confusion

Tags:

c++

c++11

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?

like image 342
bryantism Avatar asked Feb 21 '14 03:02

bryantism


1 Answers

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.

like image 134
Brian Bi Avatar answered Sep 30 '22 16:09

Brian Bi