浅拷贝:简单的赋值操作
深拷贝:在堆里重新申请空间,进行拷贝操作
浅拷贝:
#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;
}
我们新建一个指针类型的变量存放在堆区(程序员自己清理),然后在析构函数里面将堆区的数据内存清理。这时会发生什么呢?
程序直接崩了,为什么?
![](https://img-blog.csdnimg.cn/20210720194040609.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDgyNzkw,size_16,color_FFFFFF,t_70)
堆区开辟的空间被重复释放。要用深拷贝来解决。
#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;
}
这样就正确了