深拷贝、浅拷贝

浅拷贝:简单的赋值操作

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

浅拷贝:

#include<iostream>

using namespace std;
class Person
{
public:
	int m_age;
	Person()
	{
		cout << "默认构造函数" << endl;
	}
	Person(int age)
	{
		m_age = age;
		cout << "有参构造函数" << endl;
	}
	~Person()
	{
		cout << "析构函数调用" << endl;
	}
};
void test01()
{
	Person p(18);
	cout << "p    " << p.m_age << endl;
	Person p2(p);
	cout << "p2    " << p2.m_age << endl;

}
int main()
{
	test01();
	system("pause");
	return 0;
}

整个代码没有任何问题,系统自带拷贝函数。 但是将上面的代码进行一些修改。

#include<iostream>

using namespace std;
class Person
{
public:
	int m_age;
	int* m_height;
	Person()
	{
		cout << "默认构造函数" << endl;
	}
	Person(int age,int height)
	{
		m_age = age;
		m_height = new int(height);
		cout << "有参构造函数" << endl;
	}
	~Person()
	{
		//析构函数,将堆区开辟的数据做释放操作

		if (m_height != NULL)
		{
			delete m_height;
			m_height = NULL;
		}
		cout << "析构函数调用" << endl;
	}
};
void test01()
{
	Person p(18,160);
	cout << "p    " << p.m_age    << *p.m_height<<endl;
	Person p2(p);
	cout << "p2    " << p2.m_age <<*p2.m_height<< endl;

}
int main()
{
	test01();
	system("pause");
	return 0;
}

我们新建一个指针类型的变量存放在堆区(程序员自己清理),然后在析构函数里面将堆区的数据内存清理。这时会发生什么呢?

 程序直接崩了,为什么?

原因分析
​​​

 

 堆区开辟的空间被重复释放。要用深拷贝来解决。

#include<iostream>

using namespace std;
class Person
{
public:
	int m_age;
	int* m_height;
	Person()
	{
		cout << "默认构造函数" << endl;
	}
	Person(int age,int height)
	{
		m_age = age;
		m_height = new int(height);
		cout << "有参构造函数" << endl;
	}
	Person(const Person& p)
	{
		cout << "Person拷贝构造函数调用" << endl;
		m_age = p.m_age;
		m_height = new int(*p.m_height);//重新new一块内存让自己来释放
	}
	~Person()
	{
		//析构函数,将堆区开辟的数据做释放操作

		if (m_height != NULL)
		{
			delete m_height;
			m_height = NULL;
		}
		cout << "析构函数调用" << endl;
	}
};
void test01()
{
	Person p(18,160);
	cout << "p    " << p.m_age    << *p.m_height<<endl;
	Person p2(p);
	cout << "p2    " << p2.m_age <<*p2.m_height<< endl;

}
int main()
{
	test01();
	system("pause");
	return 0;
}

这样就正确了

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大家好我是覃同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值