深浅拷贝是面试经典问题,也是常见的一个坑
浅拷贝:简单的复制拷贝操作
深拷贝:在堆区重新申请空间,进行拷贝操作
#include<iostream>
using namespace std;
//浅拷贝带来的问题就是堆区内存重复释放
//浅拷贝的问题要利用深拷贝进行解决
class person
{
public:
person()
{
cout << "person 构造函数的调用" << endl;
}
person(int a,int height)
{
m_height = new int(height);
m_age = a;
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(const person& p)
//{
// m_age = p.m_age;
// cout << "person 拷贝函数的调用" << endl;
//}
~person()
{
//析构代码,将堆区开辟数据做释放操作
if (m_height != NULL)
{
delete m_height;
m_height = NULL;
}
cout << "person 析构函数的调用" << endl;
}
int m_age;
int* m_height;
};
void test01()
{
person p1(18, 160);
cout << "p1的年龄为:" << p1.m_age << "身高为:" << *p1.m_height << endl;
person p2(p1);
cout << "p2的年龄为:" << p2.m_age << "身高为:" << *p2.m_height << endl;
}
int main()
{
test01();
system("pause");
return 0;
}