C++随手笔记(十四) 空类中的默认函数,转移构造函数、转移赋值操作符、类中有指针

这段代码展示了C++中类的构造函数、复制构造函数、转移构造函数以及赋值运算符和转移赋值运算符的实现。在main函数中,创建并操作了多个Test类的对象,演示了对象间的复制和资源管理。
#include <iostream>
#include <mutex>
using namespace std;


class Test
{

public:
	Test()
	{
		if (!a)
			a = new int(5);

		cout << "构造函数" << endl;
	}

	~Test()
	{
		if (a)
		{
			delete a;
			a = nullptr;
		}
		cout << "析构函数" << endl;
	}

	Test(const Test& t)
	{
		this->a = new int(5);
		if (t.a)
			*(this->a) = *(t.a);

		cout << "复制构造函数" << endl;
	}

	Test(Test&& t)
	{
		if (t.a)
		{
			this->a = t.a;
			t.a = nullptr;
		}

		cout << "转移构造函数" << endl;
	}


	Test& operator=(const Test& t)
	{
		this->a = new int(5);
		if (t.a)
			*(this->a) = *(t.a);

		cout << "赋值运算符" << endl;

		return *this;
	 }
	Test& operator=(Test&& t)
	{
		if (t.a)
		{
			this->a = t.a;
			t.a = nullptr;
		}
		cout << "转移赋值运算符" << endl;
		return *this;
	}

public:
	int *a;

};





int main()
{
	Test a;
	*(a.a) = 10;
	Test b;
	b = a;
	cout << "b" << *(b.a) << endl;
	Test c(a);
	cout << "c" << *(c.a) << endl;


	cout << "*********************" << endl;
	Test d(std::move(a));
	cout << "d" << *(d.a) << endl;
	Test e;
	e = std::move(a);
	cout << "e" << *(e.a) << endl;



	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值