深拷贝、浅拷贝问题
概念
浅拷贝:简单的赋值拷贝操作 (有指针时注意)
深拷贝:在堆区申请空间,进行拷贝操作
浅拷贝出现时机
- 默认拷贝拷贝构造(即只要出现默认拷贝构造就是浅拷贝,一下是拷贝构造出现时机)
- 一个对象以值传递的方式传入函数体
- 一个对象以值传递的方向从函数体返回
- 一个对象需要跳过另一个方式从函数体返回
- 默认的operator=函数中
浅拷贝危害
很容易带来堆区重复释放问题,重复释放堆区内存容易造成程序崩溃。问题常出点在于类中有指针时出现,如果不做深拷贝处理,一遇到浅拷贝,在析构时程序极易崩溃。
解决方法
对于类成员为指针时,就应该重新new出一个对象来接收防止构造函数简单的赋值。
示例
#include <cstdio>
#include <iostream>
using namespace std;
class m_class {
public:
m_class()
{
cout << "调用无参构造" << endl;
};
m_class(int val)
{
a = val;
height = new int;
cout << "调用有参构造" << endl;
};
m_class(const m_class &Obj)
{
a = Obj.a;
//height = Obj.height; 浅拷贝就是执行这句(编译器默认执行),但是这会报错
height = new int(*Obj.height);
cout << "调用拷贝构造" << endl;
}
~m_class()
{
if (height!=NULL)
{
delete height;
height = NULL;
}
cout << "调用析构造" << endl;
};
int *height; //有指针时
int a;
};
int main()
{
m_class p1(10);
m_class p2(p1);
return 0;
}