c++深拷贝与浅拷贝问题:
浅拷贝:简单的赋值拷贝操作;
深拷贝:在堆区重新申请空间,再进行拷贝操作;
问题:浅拷贝会带来堆区内存被重复释放的问题,析构函数被调用多次,导致程序运行崩溃;
解决:通过深拷贝解决,在堆区重新申请内存,各自释放自己的内存,避免重复释放;
#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;
}
int m_Age;
int *m_Height;
//自己实现拷贝构造函数,来避免编译器的拷贝构造函数造成浅拷贝问题;
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;
}
};
void test01(){
Person p1(18,160);
cout << "p1的年龄为:" << p1.m_Age<<"p1身高为:"<<*p1.m_Height<< endl;
Person p2(p1);//编译器默认调用拷贝构造函数,进行浅拷贝操作
cout << "p2的年龄为:" << p2.m_Age<< "p2身高为:"<<*p2.m_Height << endl;
}
int main(){
test01();
system("pause");
}
程序运行结果: