#include <iostream>
using namespace std;
/*
右值引用只能指向右值,但想指向左值,则可以通过std::move函数将左值转换为右值(调用左值的移动构造函数),std::forward也可以
*/
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; // expect construct!
cout << "demo2:\n";
movedemo demo2 = demo; // expect copy construct!
//cout << *demo2.num << endl; //可以执行
cout << "demo3:\n";
movedemo demo3 = std::move(demo); // expect move construct!
//此时 demo.num = NULL,因此下面代码会报运行时错误
//cout << *demo.num << endl;
return 0;
}
C++ std::move
最新推荐文章于 2024-11-28 15:37:50 发布