关于深复制与浅复制

先从问题开始,如下程序是否正确,执行后的结果是?

#include <iostream>
#include <string>
using namespace std;
class A
{
	int i;
};
class B
{
public:
	A* p;
public:
	B() {p=new A;}
	~B() 
	{
		delete p;
	}
};
void sayhello(B b)
{
}
int main()
{
	B b;
	sayhello(b);
	system("pause");
	return 0;
}

结果:上述程序编译没有错误,在运行的时候会出错,因为没有进行深复制(类B的对象中含有动态申请资源,类B默认的拷贝构造函数不进行深复制)。

当一个类对象中含有堆或其他系统 资源,发生对象的复制时,相应的对象占有的资源也要进行复制,此时为深复制,若不复制这部分,则为浅复制。

为上面的程序添加一个拷贝构造函数可解决问题。当使用赋值运算符进行对象的赋值时,也会发生对象的复制,这种情况也要考虑深复制,再为上面的程序添加一个赋值运算符重载函数,进行深复制可以解决问题。程序如下:

#include <iostream>
#include <string>
using namespace std;
class A
{
	int i;
};
class B
{
public:
	A* p;
public:
	B() {p=new A;}
	B(const B&);        //拷贝构造函数
	B &operator=(const B&);
	~B() 
	{
		delete p;
	}
};
B::B(const B &b)        //深拷贝
{
	p=new A;
}
B &B::operator=(const B &b)
{
	p=new A;
	return *this;
}
void sayhello(B b)
{
}
int main()
{
	B a,b;
	B c=a;         //调用拷贝构造函数
	sayhello(b);   //调用拷贝构造函数
        c=b;           //调用赋值运算符重载函数
	system("pause");
	return 0;
}


 


 


 


#include <iostream>
#include <string>
using namespace std;
class A
{
	int i;
};
class B
{
public:
	A* p;
public:
	B() {p=new A;}
	B(const B&);
	~B() 
	{
		delete p;
	}
};
B::B(const B &b)
{
	p=new A;
}
void sayhello(B b)
{
}
int main()
{
	B b;
	B c=b;
//	sayhello(b);
	system("pause");
	return 0;
}


 

猜你喜欢

转载自blog.csdn.net/u012258911/article/details/48242769
今日推荐