#include<iostream>
using namespace std;
class person
{
public:
int m_age;
int* m_height;
person() {
cout << "person的默认构造函数调用" << endl;
}
~person() {
cout << "person的析构构造函数调用" << endl;
//析构代码,将堆区的开辟的内存释放
if (m_height != NULL)//防止野指针的出现
{
delete m_height;
m_height = NULL;
}
}
person(int age,int height) {
cout << "person的有参构造函数调用" << endl;
m_age = age;
m_height=new int(height);//堆区
}
};
void test01()
{
person p1=person(18,160);
cout << "person 的年龄为" << p1.m_age << endl;
cout << "person 的身高为" << *p1.m_height << endl;
person p2(p1);
cout << "person2 的年龄为" << p2.m_age << endl;
cout << "person2 的身高为" << *p2.m_height << endl;
}
int main()
{
test01();
return 0;
}
上述代码会自动崩溃,`person p1(p2),系统会自动进行`浅拷贝的操作
`此时程序问题出在 *m_height上
p1.m_height 如果地址是0x001的话,那么浅拷贝得到的p2.m_height 的地址也是0x001,
而在析构函数中调用了delete 同一个地址的内存被释放了两次,从而引发了错误,
注意:根据栈的先进后出原则,p2先被释放,而p1后被释放
如何解决?
使用深拷贝
```cpp
//深拷贝和浅拷贝
#include<iostream>
using namespace std;
class person
{
public:
int m_age;
int* m_height;
person() {
cout << "person的默认构造函数调用" << endl;
}
person(const person& p)
{
cout << "person拷贝构造函数的调用" << endl;
m_age = p.m_age;
//编译器自动生成的浅拷贝代码m_height = p.m_age;
//深拷贝做法:
m_height=new int(*p.m_height);
}
~person() {
cout << "person的析构构造函数调用" << endl;
//析构代码,将堆区的开辟的内存释放
if (m_height != NULL)//防止野指针的出现
{
delete m_height;
m_height = NULL;
}
}
person(int age,int height) {
cout << "person的有参构造函数调用" << endl;
m_age = age;
m_height=new int(height);//堆区
}
};
void test01()
{
person p1=person(18,160);
cout << "person 的年龄为" << p1.m_age << endl;
cout << "person 的身高为" << *p1.m_height << endl;
person p2(p1);
cout << "person2 的年龄为" << p2.m_age << endl;
cout << "person2 的身高为" << *p2.m_height << endl;
}
int main()
{
test01();
return 0;
}
总结:注意什么时候写析构函数,如需要释放自己开辟的内存的时候.注意开辟地址释放的时候不要重复释放.