【C++】类和对象(六)

深拷贝和浅拷贝

注意:深拷贝和浅拷贝指的是在拷贝构造函数中的操作。

深拷贝是面试经典问题,也是常见的一个坑。

浅拷贝:简单的赋值拷贝操作。

深拷贝:在堆区重新申请空间,进行拷贝操作。

示例://浅拷贝

#include<iostream>
using namespace std;
class  person
{
public:
	person()
	{
		cout << "person的默认构造函数调用" << endl;
	}
	person(int age, int height)
	{
		m_age = age;
		m_height = height;
	}
	~person()
	{
		cout << "person的析构函数调用" << endl;
	}
	int m_age;
	int m_height;
};
int main()
{
	person p1(22, 180);
	person p2(p1);
	cout << "p1的年龄为:" << p1.m_age << "p1的身高为:" << p1.m_height << endl;
	cout << "p2的年龄为:" << p2.m_age << "p2的身高为:" << p2.m_height << endl;
	return 0;
}

结果:

代码:

#include<iostream>
using namespace std;
class  person
{
public:
	person()
	{
		cout << "person的默认构造函数调用" << endl;
	}
	person(int age, int height)
	{
		m_age = age;
		*m_height = height;
	}
	~person()
	{
		//析构代码将堆区开辟数据做释放操作
		if (m_height != NULL)
		{
			delete m_height;
			m_height = NULL;
		}
		cout << "person的析构函数调用" << endl;
	}
	int m_age;//年龄
	int *m_height;//身高
};
int main()
{
	person p1(22, 180);
	person p2(p1);
	cout << "p1的年龄为:" << p1.m_age << "p1的身高为:" << p1.m_height << endl;
	cout << "p2的年龄为:" << p2.m_age << "p2的身高为:" << p2.m_height << endl;
	return 0;
}

结果:

为什么会出现异常呢?

我们知道:当我们定义有参构造函数时,C++不再提供无参构造函数,但是会提供默认拷贝构造函数,而默认拷贝构造函数,对属性进行值拷贝。所以p1的指针m_height和p2的指针m_height值相同,所以当执行:

if (m_height != NULL)
{
	delete m_height;
	m_height = NULL;
}

会导致堆区的内存被重复释放。所以这才是导致异常的原因。

浅拷贝的问题要利用深拷贝进行解决。

//自己实现拷贝构造函数解决浅拷贝带来的问题。

person(const person& p)
{
	cout << "person 拷贝构造函数调用" << endl;
	m_age = p.m_age;
	//m_height=p.m_height;编译器默认实现就是这行代码
	//深拷贝操作
	m_height = new int(*p.m_height);
}

代码:


#include<iostream>
using namespace std;
class  person
{
public:
	person()
	{
		cout << "person的默认构造函数调用" << endl;
	}
	person(int age, int height)
	{
		m_age = age;
		m_height = new int (height);
	}
	person(const person& p)
	{
		cout << "person 拷贝构造函数调用" << endl;
		m_age = p.m_age;
		//m_height=p.m_height;编译器默认实现就是这行代码
		//深拷贝操作
		m_height = new int(*p.m_height);
	}
	~person()
	{
		//析构代码将堆区开辟数据做释放操作
		if (m_height != NULL)
		{
			delete m_height;
			m_height = NULL;
		}
		cout << "person的析构函数调用" << endl;
	}
	int m_age;//年龄
	int *m_height;//身高
};
int main()
{
	person p1(22, 180);
	person p2(p1);
	cout << "p1的年龄为:" << p1.m_age << "p1的身高为:" << *p1.m_height << endl;
	cout << "p2的年龄为:" << p2.m_age << "p2的身高为:" <<* p2.m_height << endl;
	return 0;
}

结果:

总结:如果类中的成员属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值