移動構造函數和移動賦值與拷貝構造函數和賦值構造函數的比較


首先看拷貝構造函數:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM