深拷贝和浅拷贝
首先明确一个思想就是都是利用拷贝构造函数新创建了一个对象。
区别:
深拷贝中对于对象中的指针不仅会创建一个新的指针变量还会创建一个新的指针指向的区域,所指的值是相同的。
浅拷贝只会创建一个新的指针变量,指的内容是相同的。
作用:
防止对象中的指针所指的堆区域被多次释放。
(被拷贝的对象被 delete 掉了,它指针所指的区域也就被释放了,但是拷贝的对象不知道指针所指的区域被释放了)
#include<iostream>
#include<cstdio>
using namespace std;
class T{
public:
int age;
int *p_height;
public:
T(){
cout<<"无参构造函数"<<endl;
}
T(int a, int height){
age = a;
p_height = new int(height); // 相当于在堆区创建数据
cout<<"有参构造函数"<<endl;
}
// 拷贝构造函数->浅拷贝(编译器默认实现,会出现堆空间的 p_height 被多次释放的错误)
// T(const T &t){
// age = t.age;
// p_height = t.p_height;
// cout<<"浅拷贝构造函数"<<endl;
// }
// 拷贝构造函数->深拷贝
T(const T &t){
age = t.age;
p_height = new int(*t.p_height);
cout<<"深拷贝构造函数"<<endl;
}
~T(){
if(p_height!=nullptr){
delete(p_height);
p_height = nullptr; //防止野指针
}
cout<<"析构函数"<<endl;
}
};
void f()
{
T t1 = T(10,20);
T t2 = T(t1);
*t1.p_height = 30; // 若为深拷贝,此值不会影响 t2 的值,若为浅拷贝则会影响 t2 的值
cout<<*t2.p_height<<endl;
}
int main()
{
f();
return 0;
}