指定派生类的析构函数时,std :: move不起作用

时间:2018-12-27 14:52:08

标签: c++

我试图将一个实例移动到另一个实例,如下所示:

#include <iostream>

class student {
public:
    student() = default;
    student(const student& student) {
        std::cout << "copy student" << std::endl;
    }
    student(student&& student) {
        std::cout << "move student" << std::endl;
    }
    virtual ~student() = default;
};

class undergraduate: public student {
public:
    undergraduate(): student() {}
    ~undergraduate() override = default; // removing this line will make std::move work
};

int main() {
    undergraduate student;
    undergraduate student1 = std::move(student);
}

以下是输出:

copy student

如您所见,std::move无效,student被复制而不是被移动,但是,如果我删除了undergraduate的析构函数,即以下行:

~undergraduate() override = default; // removing this line will make std::move work

输出将变为move student,表示std::move有效。为什么?指定派生类的析构函数时,std::move为什么不起作用?

1 个答案:

答案 0 :(得分:39)

指定类的析构函数会禁止自动生成move构造函数和move赋值。您可以使用= default来还原它们:

class undergraduate: public student {
public:
    undergraduate(): student() {}
    ~undergraduate() override = default;

    undergraduate(const undergraduate&) = default;
    undergraduate& operator=(const undergraduate&) = default;

    undergraduate(undergraduate&&) = default;
    undergraduate& operator=(undergraduate&&) = default;
};

霍华德·辛南特(Howard Hinnant)为他的您想要了解的有关移动语义学的所有知识(以及其中的一些内容)” 演示文稿:

enter image description here