移动拷贝构造函数和移动赋值函数的写法

#include"pch.h"
#include<iostream>

using namespace std;
class A
{
public:
	A(int _X, int *_P) :x(_X),p(new int(*_P)) { cout << "构造函数" << endl; };
	A(const A &a) 
	{
		if (this == &a)
		{
			cout << "左值——拷贝构造函数" << endl;
			*this = a;
		}
		else
		{
			x = a.x;
			delete p;
			p = new int(*a.p);
			cout << "左值——拷贝构造函数" << endl;
		}
		
	}
	A &operator=(const A &a)
	{
		if (this == &a)
		{
			cout << "自己赋值给自己" << endl;
			return *this;
		}
		else
		{
			cout << "左值——赋值函数" << endl;
			x = a.x;
			*p = *a.p;//赋值的精髓——在于只赋值内容,不赋值指针;因为赋值的前提:是两个对象都已建立
			return *this;
		}

	}


	A(A &&a) //移动拷贝构造函数
	{
		x = a.x;
		delete p;移动拷贝构造函数,
		p = a.p;
		a.p = nullptr;
		cout << "右值——拷贝构造函数" << endl;
	}
	A &operator=(A &&a)//移动赋值函数
	{
		if (this == &a)
		{
			cout << "自己赋值给自己" << endl;
			return *this;
		}
		else
		{
			cout << "右值——赋值函数" << endl;
			x = a.x;
			delete p;
			p = a.p;
			a.p = nullptr;
			return *this;
		}
	}

	~A()
	{
		delete p;
		cout << "析构函数" << endl;
	}
	void show()
	{
		cout << "x=" << x << endl;
		cout << "*p=" << *p << endl;
		cout << "————————" << endl;
	}

private:
	int x;
	int *p;
};
void show_1(A &&a)
{
	a.show();
}
void show_1(A &a)
{
	a.show();
}
int  g= 3;
int main()
{
	int x = 2;
	int y = 111;
	A a(10,&x);
	A b(60,&y);

	
	A c = a;			//调用普通拷贝构造函数
	A e(b);				//调用普通拷贝构造函数
	c = c;				//调用左值赋值函数
	A d = std::move(a); //调用移动拷贝构造函数
	//移动拷贝构造函数,将a转移到d之后,对象a就失效了,这也是和普通的拷贝构造函数的区别;;
	c = std::move(b);		//调用移动赋值函数
	cout << "————————————" << endl;
	//a.show();//这句会报错,因为
	//b.show();
	c.show();


	show_1(std::move(a));
	show_1(std::move(b));
	show_1(std::move(c));
	show_1(c);

	//show_1(std::move(d));

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值