深拷贝和浅拷贝
定义
- 浅拷贝:简单的赋值拷贝操作
- 深拷贝:堆区申请空间进行拷贝操作
例子
#include<iostream>
using namespace std;
class Person
{
public:
Person();
~Person();
Person(int age);
Person(int age, int height);
Person(const Person& p);
int m_Age;
int* m_Height;
private:
};
Person::Person()
{
cout << "person的默认构造函数调用" << endl;
}
Person::Person(int age)
{
m_Age = age;
cout << "person的有参构造函数调用" << endl;
}
Person::Person(int age, int height)
{
m_Age = age;
m_Height = new int(height);
cout << "person的多参构造函数调用" << endl;
}
//解决浅拷贝带来的重复释放内存的问题
Person::Person(const Person& p) {
cout << "person拷贝构造函数调用" << endl;
m_Age = p.m_Age;
//m_Height = p.m_Height; 编译器默认实现
//深拷贝操作
if (p.m_Height != NULL)
{
m_Height = new int(*p.m_Height);
}
}
Person::~Person()
{
//析构函数将堆区开辟的数据进行释放
if (m_Height != NULL)
{
delete m_Height;
m_Height = NULL;
}
cout << "person的析构函数调用" << endl;
}
void test() {
Person p1(18);
cout << "p1 的年龄为:"<< p1.m_Age << endl;
Person p2(p1);
cout << "p2 的年龄为:" << p2.m_Age << endl;
Person p3(18,180);
cout << "p3 的年龄为:" << p3.m_Age << " p3 的身高为:" << *p3.m_Height << endl;
Person p4(p3);
cout << "p4 的年龄为:" << p4.m_Age << " p4 的身高为:" << *p4.m_Height << endl;
}
int main() {
test();
system("pause");
return 0;
}
问题与解决
浅拷贝带来的重复释放堆区问题,可利用深拷贝在堆区创建新内存进行解决
总结
如果属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题