首先看拷貝構造函數:
//拷貝構造函數
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;
}
