派生类的Move构造函数混淆

时间:2014-02-21 03:32:19

标签: c++ c++11

我知道在c ++移动构造函数中移动语义,但在这里我有一些困惑:

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;
    }
    // ...
};

移动构造函数Base(std :: move(x)),x已经转换为rvalue引用,怎么做vec(std :: move(x.vec))?? 仍然x存在?

1 个答案:

答案 0 :(得分:3)

Base的移动构造函数可能具有原型Base(Base&& b),因此当您在构造函数中调用Base(std::move(x))时,rvalue std::move(x)的类型为Derived },隐式转换为Base类型的右值。 Base的移动构造函数会看到Base的右值引用,因此会将Base的成员移出xx的其他成员尚未移出,因此以下移动初始化仍然有效。

移动构造和移动分配不会使对象无效。移动后仍应满足对象的不变量,以便其析构函数能够正常工作。