C++的浅拷贝和深拷贝

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

  • 浅拷贝:简单的赋值拷贝操作
  • 深拷贝:在堆区重新申请空间,进行拷贝工作

1、

class Person {
public:
	Person() {
		cout << "Person的默认构造函数调用" << endl;
	}

	Person(int age,int height) {
		m_Age = age;
		m_Height = new int (height);
		cout << "Person的有参构造函数调用" << endl;
	}

	~Person() {
		cout << "Person的析构函数调用" << endl;
	}
public:
	int m_Age;
	int* m_Height;

};

void test01(){
	Person p1(18,180);
	cout << "p1的年龄为: " << p1.m_Age
		 << "p1的身高为: " << p1.m_Height << endl;
	Person p2(p1);
	cout << "p2的年龄为: " << p1.m_Age
		 << "p2的身高为: " << p1.m_Height << endl;
}

上面就是一个简单的浅拷贝代码,
输出为:
在这里插入图片描述
2、
我们把上述代码稍作修改:

class Person {
public:
	Person() {
		cout << "Person的默认构造函数调用" << endl;
	}

	Person(int age,int height) {
		m_Age = age;
		m_Height = new int (height);  //用指针接受这个堆区的数据
		cout << "Person的有参构造函数调用" << endl;
	}

	~Person() {
		// 析构代码:将堆区开辟数据做释放操作
		if (m_Height != NULL) {
			delete m_Height;
			m_Height = NULL; // 置空指针,防止出现野指针
		}
		cout << "Person的析构函数调用" << endl;
	}
public:
	int m_Age; //年龄
	int* m_Height; //身高

};

void test01(){
	Person p1(18,180);
	cout << "p1的年龄为: " << p1.m_Age
		 << "p1的身高为: " << *p1.m_Height << endl;
	Person p2(p1);
	cout << "p2的年龄为: " << p1.m_Age
		 << "p2的身高为: " << *p1.m_Height << endl;
}

然而程序出现崩溃:
在这里插入图片描述
为什么呢?
在这里插入图片描述
我们假设开辟的堆区地址为0x0011,堆区是先进后出,所以p2先进行析构,释放数据,然后p1进行析构,释放的时候,发现地址为0x0011的数据已经被p2释放掉了,所以程序出现崩溃。

  • 浅拷贝带来的问题就是堆区的内存重复释放
  • 浅拷贝的问题要利用深拷贝进行解决

所以要我们自己写一个拷贝构造函数,自己申请一块内存,这个内存存放的数据和刚才地址为0x0011的数据相同。
在这里插入图片描述
3、问题解决。

class Person {
public:
	Person() {
		cout << "Person的默认构造函数调用" << endl;
	}

	Person(int age,int height) {
		m_Age = age;
		m_Height = new int (height);  //用指针接受这个堆区的数据
		cout << "Person的有参构造函数调用" << endl;
	}

	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;
	}
public:
	int m_Age; //年龄
	int* m_Height; //身高

};

void test01(){
	Person p1(18,180);
	cout << "p1的年龄为: " << p1.m_Age
		 << "p1的身高为: " << *p1.m_Height << endl;
	Person p2(p1);
	cout << "p2的年龄为: " << p1.m_Age
		 << "p2的身高为: " << *p1.m_Height << endl;
}

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

发布了59 篇原创文章 · 获赞 15 · 访问量 1605

猜你喜欢

转载自blog.csdn.net/weixin_43867777/article/details/104253445