拷贝、移动构造

该篇博客探讨了C++中的类实例化过程,包括构造函数、拷贝构造函数和移动构造函数的使用。通过示例代码展示了如何初始化对象,以及在对象传递和返回时,如何利用拷贝和移动构造函数优化性能。同时还涉及了对象生命周期中的析构函数。
摘要由CSDN通过智能技术生成
#include <iostream>
using namespace std;

class temp
{
private:
	char *a ;
public:
	temp(char c, char b) 
	{ 
		a = new char[2];
		
		a[0] = c;
		a[1] = b; 
		cout << "构造" << endl;
	}
	temp(temp &t):a(t.a)
	{
		a = new char[2];
		cout << "拷贝" << endl;
	}

	temp(temp &&t):a(t.a)
	{
		t.a = NULL;
		cout << "移动" << endl;
	}
	void show(void)
	{
		//cout << this->a[0] << endl;
		printf("%d\r\n", this->a[0]);
	}

	~temp() { cout << "析构" << endl; delete[] a; }
};

temp get(void)
{
	temp d(3, 4);
	cout << "666" << endl;
	return d;
}

int main(void)
{
	temp c(1, 2);//构造
	temp b = c;//拷贝
	//temp b = move(c);//左值强制转化为右值,将拷贝改进为移动
	c.show();
	temp d = get();//移动
	
	system("pause");
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值