如果数据开在堆上 那么浅拷贝可能出现重复释放的情况 所以我们必须学会使用深拷贝
[] [c++]1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| #include<bits/stdc++.h> using namespace std;
//深拷贝与浅拷贝 class Person { public: Person() { cout<<"Person默认构造函数的调用"<<endl; } ~Person() { //析构代码还可以释放堆区的数据 体现作用 if(m_Height!=NULL) { delete m_Height; m_Height=NULL;//野指针置空 } cout<<"Person析构函数的调用"<<endl; } Person(int age,int height) { m_Age=age; m_Height=new int(height);//数据开在堆上 new返回的是地址 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); }
int m_Age; int *m_Height; };
void test01() { Person p1(18,160); cout<<"p1的年龄为:"<<p1.m_Age<<endl; cout<<"p1的身高为:"<<*p1.m_Height<<endl; Person p2(p1); cout<<"p2的年龄为:"<<p2.m_Age<<endl; cout<<"p2的身高为:"<<*p2.m_Height<<endl; //我们没提供拷贝构造函数 但是编译器自己提供了(浅拷贝) //注意 先构造的后析构 此时浅拷贝带来的问题是堆区的重复释放 //因为p2是完全由p1复制的 p2先释放 清空了堆区中相应数据 而p1指针不为空 二次释放 所以出错 //可以用深拷贝来解决 让p2m_Height指向另一个地址 但是数值和p1一样 参照49行 } int main() { test01(); return 0; }
|