C++移动构造函数

类似拷贝构造函数,移动构造函数的第一个参数是该类类型的一个引用。 不同于拷贝构造函数的是,这个引用参数在移动构造函数中是一个右值引用
除了完成资源移动,移动构造函数还必须确保移后源对象处于这样一个状态——销毁它是无害的。一旦资源完成移动,源对象必须不再指向被移动的资源——这些资源的所有权已经归属新创建的对象。


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

using namespace std;

class IntNum
{
public:
	IntNum(int x = 0) :xptr(new int(x))              //构造函数
	{
		cout << "Calling constructor...\n";
	}
	IntNum(const IntNum &n) :xptr(new int(*n.xptr)) //拷贝构造函数
	{
		cout << "Calling copy constructor...\n";
	}
	IntNum(IntNum &&n) :xptr(new int(*n.xptr))     //移动构造函数(&&表示右值引用,即将消亡的变量)
	{
		n.xptr = nullptr;   //销毁源对象
		cout << "Calling move constructor...\n";
	}
	int getInt() { return *xptr; }
	~IntNum() 
	{
		delete xptr;
		cout << "Destructing...\n";
	}
private:
	int *xptr;
};
IntNum GetNum()    //返回创建的IntNum对象
{
	IntNum a(9); 
	return a;
}

int main()
{
	cout << GetNum().getInt() << endl;
	return 0;
}

在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值