C++系列-浅拷贝和深拷贝

浅拷贝和深拷贝

如果属性有在堆区开辟内存的,一定要自己提供拷贝构造函数,进行深拷贝,以免堆区内存重复释放。

浅拷贝

  • 浅拷贝会带来的问题是堆区空间重复释放
cpp 复制代码
因为是浅拷贝,在调用第二个对象的析构函数时,会报错
code:
	#include<iostream>
	using namespace std;
	#include"circle.h"
	class Person
	{
	public:
		int age;
		int* p_height;
		Person(int ref_age, int ref_height)
		{
			age = ref_age;
			p_height = new int(ref_height);
			cout << "堆区开辟的地址为: "  << p_height << endl;
			cout << "有参构造函数被调用," << "年龄是:" << age << ",身高是:" << *p_height << endl;
		}
		~Person()
		{
			cout << p_height << endl;
			if(p_height != NULL)
			{
				delete p_height;
				p_height = NULL;
			}
			cout << "析构函数被调用" << endl;
		}
	};
	void test1()
	{
		Person p1(11, 160);
		Person p2(p1);
	}
	void main()
	{
		test1();
		system("pause");
	}

result:
	堆区开辟的地址为: 0000020FB4F36310
	有参构造函数被调用,年龄是:11,身高是:160
	0000020FB4F36310
	析构函数被调用
	0000020FB4F36310
	报错

深拷贝

  • 重新在堆区申请内存空间
cpp 复制代码
code:
	#include<iostream>
	using namespace std;
	#include"circle.h"
	class Person
	{
	public:
		int age;
		int* p_height;
		Person(int ref_age, int ref_height)
		{
			age = ref_age;
			p_height = new int(ref_height);
			cout << "堆区开辟的地址为: "  << p_height << endl;
			cout << "有参构造函数被调用," << "年龄是:" << age << ",身高是:" << *p_height << endl;
		}
	
		Person(const Person& ref_p)
		{
			age = ref_p.age;
			p_height = new int(*ref_p.p_height);		// 堆区重新申请空间
			//p_height = ref_p.p_height;	//编译器默认实现的是这行代码
			cout << "拷贝构造函数被调用, " << "堆区开辟的地址为:" << p_height << endl;
		}
	
		~Person()
		{
			cout << p_height << endl;
			if(p_height != NULL)
			{
				delete p_height;
				p_height = NULL;
			}
			cout << "析构函数被调用" << endl;
		}
	};
	
	void test1()
	{
		Person p1(11, 160);
		Person p2(p1);
	}
	
	void main()
	{
		test1();
		system("pause");
	}
result:
	堆区开辟的地址为: 0000021DED9361D0
	有参构造函数被调用,年龄是:11,身高是:160
	拷贝构造函数被调用, 堆区开辟的地址为:0000021DED936990
	0000021DED936990
	析构函数被调用
	0000021DED9361D0
	析构函数被调用
相关推荐
blasit8 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_1 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星2 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20215 天前
信号量和信号
linux·c++