[C++]通过构造函数体会右值引用

在下面的构造函数和等号重载中,分别使用了左值的方式和右值的方式
可以看到,右值的方式相比左值,少了拷贝操作,性能更优

源代码

#include "pch.h"
#include<iostream>
#include <stdio.h>
using namespace std;
int cnt = 0;
class myc
{
	int id=0;//对象id,只在构造时自增
	char* str;//没有实际内容,只用来分配空间和展示地址
	size_t s;//内存大小
public:
	void show()
	{
		cout << "	id: " << id << endl;
		cout <<"	address: " << &str << endl;
		cout << "	size_t: " << s << endl;
		cout << "--------------------------------------------------" << endl;
	}
	myc(size_t x)
	{
		id = ++cnt;
		cout << "	构造:" << id<<endl;
		str = new char[x];
		s = x;
	}
	~myc()
	{
		cout << "	析构:" <<id<< endl;
		if (str != nullptr)
		{
			delete[] str;
			str = nullptr;
		}
		s = 0;
	}
	myc(const myc& tmp)
	{
		id = ++cnt;
		cout << "	拷贝构造:" << tmp.id<<" copy to " << id << endl;
		s = tmp.s;
		str = new char[s];
		memcpy(str, tmp.str, tmp.s *sizeof(char));
	}
	myc(myc&& tmp)
	{
		id = ++cnt;
		cout << "	移动构造:" <<tmp.id<<" move to "<<id << endl;
		s = tmp.s;
		str = tmp.str;
		tmp.str = nullptr;
		tmp.s = 0;
	}
	myc& operator=(myc& tmp)
	{
		cout << "	copy left " <<tmp.id<<" to "<<id << endl;
		if (str != nullptr && this != &tmp)
		{
			delete[] str;
		}
		s = tmp.s;
		str = new char[s];
		memcpy(str, tmp.str, tmp.s * sizeof(char));
		return *this;
	}
	myc& operator=(myc&& tmp)
	{
		cout << "	copy right " <<tmp.id<<" to " << id << endl;
		if (str != nullptr && this != &tmp)
		{
			delete[] str;
		}
		str = tmp.str;
		s = tmp.s;
		tmp.str = nullptr;
		tmp.s = 0;
		return *this;
	}
};
myc getTmp(size_t ll)
{
	return ll > 0 ? myc(ll) : myc(100);

}
int main()
{
	cout << "操作 a:" << endl;
	myc a(10);
	cout << "show a:" << endl;
	a.show();
	cout << "操作 b:" << endl;
	myc b(a);
	cout << "show b:" << endl;
	b.show();
	cout << "操作 c:" << endl;
	myc c(5);
	cout << "show c:" << endl;
	c.show();
	//这里是拷贝赋值操作
	cout << "操作 c=a:" << endl;
	c = a;
	cout << "show c:" << endl;
	c.show();
	//这里是搬运赋值操作,右值引用
	//为b赋了getTmp返回的临时变量(右值)
	cout << "操作 b=getTmp(100):" << endl;
	//这里会有两次析构是因为重载的=中包含一次删除操作,这会触发析构函数
	b = getTmp(100);
	cout << "show b:" << endl;
	b.show();
	cout << "操作 myc d=getTmp(20):" << endl;
	myc d = getTmp(20);
	cout << "show d:" << endl;
	d.show();
	cout << "end" << endl;
	return 0;
}
}

运行结果

在这里插入图片描述
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值