我试图将一个实例移动到另一个实例,如下所示:
#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
为什么不起作用?
答案 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)为他的您想要了解的有关移动语义学的所有知识(以及其中的一些内容)” 演示文稿: