1.浅拷贝:
简单的赋值拷贝操作
2.深拷贝:
在堆区重新申请空间,进行拷贝操作
3.深拷贝和浅拷贝的代码举例:
浅拷贝的问题(浅拷贝被重复释放,导致程序崩溃):
#include<iostream>
using namespace std;
//深拷贝和浅拷贝
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;
}
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;
}
采取深拷贝解决浅拷贝的问题:
#include<iostream>
using namespace std;
//深拷贝和浅拷贝
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;
}
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;
}