C++ 深拷貝和淺拷貝std::move移動構造函數,移動賦值函數

一個class如果包含了普通指針成員的話那就必須實現(如果是智能指針則則沒有必要)特別是複製構造函數和移動構造函數不要忘記

  1. 構造函數,
  2. 析構函數,
  3. 拷貝構造函數,
  4. 移動構造函數,
  5. 移動賦值函數
  6. 拷貝複製函數

上述缺少一個都會造成內存泄漏;

=delete  =default 關鍵字一般只會用在上述幾個函數,普通函數幾乎不用,

一個class 對象對容器的操作在沒有實現移動構造函數的情況之下,就會調用拷貝構造函數實現push_back(),實現移動構造函數的情況之下,就會調用移動構造函數實現push_back(),賦值表達式也是一樣;

#include<iostream>
#include<list>
using namespace std;
class A
{
private:
	int a;
	int *buf;
public:

	A(){
		a = 0;
		buf = new int[100];
		cout << "A" << endl;
	}
	~A(){
		if (buf != nullptr)
		{
			delete[]buf;
			cout << "~A" << endl;
		}
	}
	A(const A &tmp) //= delete;
	{
		this->a = a;
		this->buf = new int[100];
		cout << "copy A" << endl;
		//return *this;
	}

	

	A( A &&tmp)
	{
		cout << "move A" << endl;
		this->a = a;
		this->buf = tmp.buf;
		tmp.buf = nullptr;
	}
	A operator=(const A &temp)// = delete;
	{
		this->a = a;
		this->buf = new int[100];
		cout << "= A" << endl;
		return *this;
	}
	
	A operator=( A &&temp)
	{
		cout << "move =  A" << endl;
		this->a = a;
		this->buf = temp.buf;
		temp.buf = nullptr;
		return std::move(*this);
	}
	A copyA(A&a)
	{
		return std::move(a);
	}
};
int main()
{
	list<A> list_;
	for (auto a : { 1, 2, 4 })
	{
		cout << "-------begin------" << endl << endl;
		list_.push_back(A());
	}
	cout << "-------1------" << endl;
	list_.clear();
	cout << "-------2------" << endl;
	{
		A a;
		A b = a;
		const A c;
		A d = c;
	}
	getc(stdin);
	return 1;
}

 

 

智能指針測試代碼

 

#include<iostream>
#include<list>
#include<memory>
using namespace std;

int cnt=0;//記錄C的分配析構次數
class C
{
public :
	 int c;
public:
	C(int aa) :c(aa)
	{
		cnt++;
		cout << "C" << endl;
	}
	~C()
	{
		cnt--;
		cout << "~C" << endl;
	}
	C(const C&)
	{
		cout << "C copy" << endl;
		cnt++;
	}
};
int a=0;//記錄B的分配析構次數
class B
{
public:
	
	std::shared_ptr<C> buf=nullptr;
public:

	B(){
		
		buf = make_shared<C>(3);
		cout << "B" << endl;
		a++;
	}
	~B(){
		if (buf != nullptr)
		{
			a--;
			cout << "~B" << endl;
		}
	}


	//B(const B &tmp) = delete;
	//{
	//	
	//	this->buf = make_shared<C>(*tmp.buf);
	//	a++;
	//	cout << "copy B" << endl;
	//	//return *this;
	//}

	//B(B &&tmp)
	//{
	//	cout << "move B" << endl;
	//	this->a = a;
	//	this->buf = tmp.buf;
	//	tmp.buf = nullptr;
	//}



	B operator=(const B &temp)// = delete;
	{
		a++;
		
		this->buf = make_shared<C>(*temp.buf);
		cout << "= B" << endl;
		return *this;
	}

	B operator=(B &&temp)
	{
		cout << "move =  B" << endl;
		
		this->buf = temp.buf;
		temp.buf = nullptr;
		return std::move(*this);
	}
	
};

int main()
{
	list<B> list_;
	for (auto a : { 1, 2, 4 })
	{
		cout << "-------begin------" << endl << endl;
		list_.push_back(B());
	}
	cout << "-------1------" << endl;
	list_.clear();
	cout << "-------2------" << endl;
	{
		//B a;
		//B b = a;
		
	}
	cout << "a = " << a << "cnt = " << cnt << endl;
	getc(stdin);
	return 1;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章