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
	析构函数被调用
相关推荐
SomeOtherTime18 小时前
Rust 面向对象介绍(AI回答)
开发语言·python·rust
wo_jack19 小时前
C++ 入门笔记(十七):list 入门 —— 为什么 list 不能 sort?
数据结构·c++·面试·stl·list
zh_xuan19 小时前
kotlin常见面试题
开发语言·kotlin·面试题
青少儿编程课堂20 小时前
蓝桥杯青少组图形化 + 全国青少年信息素养大赛 + 电子学会Scratch考级:校园连连看解析
c++·python·算法·bfs·信息学竞赛
草莓熊Lotso20 小时前
【C++ 基于微服务的即时通讯系统】文件存储子服务实战:UUID生成、文件IO封装与全接口单元测试
开发语言·网络·数据库·c++·微服务·架构·单元测试
huaqianzkh21 小时前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#
沐晓时光1 天前
C语言入门,内存函数知识讲解
c语言·开发语言
David猪大卫2 天前
【C++修炼】map 和 set 的使用
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
HPtiger2 天前
C++ 入门笔记:从 C 到 C++ 的核心过渡(命名空间、输入输出、缺省参数、重载、引用、内联)
c语言·c++·学习
fengci.2 天前
CTF2MISC中等部分
开发语言·前端·学习