移动构造函数和移动赋值与拷贝构造函数和赋值构造函数的比较
首先看拷贝构造函数: //拷贝构造函数 A(A& t) { if(t.text!=NULL) { int len=strlen(t.text); text=new char[len+1]; strcpy(text,t.text); } } 拷贝构造函数中实现了深拷贝处理。再看移动构造函数: //移动构造函数 A(A&& t) { if(t.text!=NULL) { text=t.text; t.text=NULL; } } 代码构造和拷贝构造函数类似,但是内存的处理不是拷贝而是转移。注意参数类型是右值引用。 移动赋值运算符 赋值运算符的情况和构造函数类似,还是先考察普通的赋值运算符: //拷贝赋值运算符 A& operator=(const A& rhs) { if(this!=&rhs) { free(); if(rhs.text!=NULL) { int len=strlen(rhs.text); text=new char[len+1]; strcpy(text,rhs.text); } } return *this; } 再看移动赋值运算符: //移动赋值运算符 A& operator=(A&& rhs)noexcept { if(this!=&rhs) { free(); text=rhs.text; rhs.text=NULL; } reeturn *this; }