每日C++小程序小研究·4·2023.7.27

右值引用、移动构造函数

#include<string>
#include<iostream>
using namespace std;
class Dog
{
public:
	Dog(){};
 
	Dog(int age,string name) :m_age(new int(age)), m_name(name){}
 
	Dog(Dog& d):m_age(d.m_age),m_name(d.m_name) 
	{
		cout << "我是拷贝构造函数······" << endl;
	}
	Dog(Dog&& d) :m_age(d.m_age), m_name(d.m_name) 
	{
		d.m_age = nullptr;
		cout << "我是移动构造函数······" << endl;
	}
 
	int* m_age;
	string m_name;
};

使用:

#include"construct.h"
int main()
{
	int age = 19;
	string name = "小狗狗";
	Dog d1(age, name);
	cout << "d1:" <<* d1.m_age << d1.m_name << endl;
 
	Dog d2(move(d1));
 
	bool is = d1.m_age == nullptr;
	cout << is << endl;
 
	cout << "d2.age:" << *d2.m_age <<endl<< "d2.name:" <<d2.m_name << endl;
	return 0;
}

移动构造运行成功,d1销毁了,d2获取到了d1的内存。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值