move 函数
move 函数
move(arg)
其中,
#include <iostream>
using namespace std;
class movedemo{
public:
movedemo():num(new int(0)){
cout<<"construct!"<<endl;
}
//拷贝构造函数
movedemo(const movedemo &d):num(new int(*d.num)){
cout<<"copy construct!"<<endl;
}
//移动构造函数
movedemo(movedemo &&d):num(d.num){
d.num = NULL;
cout<<"move construct!"<<endl;
}
public: //这里应该是 private,使用 public 是为了更方便说明问题
int *num;
};
int main(){
movedemo demo;
cout << "demo2:\n";
movedemo demo2 = demo;
//cout << *demo2.num << endl; //可以执行
cout << "demo3:\n";
movedemo demo3 = std::move(demo);
//此时 demo.num = NULL,因此下面代码会报运行时错误
//cout << *demo.num << endl;
return 0;
}
程序执行结果为:
construct!
demo2:
copy construct!
demo3:
move construct!
通过观察程序的输出结果,以及对比
#include <iostream>
using namespace std;
class first {
public:
first() :num(new int(0)) {
cout << "construct!" << endl;
}
//移动构造函数
first(first &&d) :num(d.num) {
d.num = NULL;
cout << "first move construct!" << endl;
}
public: //这里应该是 private,使用 public 是为了更方便说明问题
int *num;
};
class second {
public:
second() :fir() {}
//用 first 类的移动构造函数初始化 fir
second(second && sec) :fir(move(sec.fir)) {
cout << "second move construct" << endl;
}
public: //这里也应该是 private,使用 public 是为了更方便说明问题
first fir;
};
int main() {
second oth;
second oth2 = move(oth);
//cout << *oth.fir.num << endl; //程序报运行时错误
return 0;
}
/**
construct!
first move construct!
second move construct
*/
程序中分别构建了
- 程序第
31 行:由于oth 为左值,如果想调用移动构造函数为oth2 初始化,需先利用move() 函数生成一个oth 的右值版本; - 程序第
22 行:oth 对象内部还包含一个first 类对象,对于oth.fir 来说,其也是一个左值,所以在初始化oth.fir 时,还需要再调用一次move() 函数。