浅复制和深复制的区别

浅复制是在复制这个对象的时候,让新旧对象指向同一个外部内容。

深复制是在复制这个对象的时候,为新对象制作了外部对象的独立复制。


浅复制的问题

#include <iostream>
#include <string.h>

using namespace std;
class Test
{
public:
	char *buf;
	Test()
	{
		buf = NULL;
	}
	Test(const char *str)
	{
		buf = new char[strlen(str) + 1];
		strcpy(buf, str);
	};
	// Test(Test &test)
	// {
	// 	cout << "copy create" << endl;
	// 	buf = new char[strlen(test.buf) + 1];
	// 	strcpy(buf, test.buf);
	// }
	virtual ~Test()
	{
		if (buf != NULL)
		{
			cout << "free Test" << endl;
			delete buf;
			buf = NULL;
		}
	}
	
};

int main(int argc, char const *argv[])
{
	Test t1("hello");
	Test t2 = t1;
	cout << t1.buf << endl;
	cout << t2.buf << endl;

	cout << "t1.buf == t2.buf ? " << (t1.buf == t2.buf? "yes" : "no") << endl;

	return 0;
}


发生错误,运行结果是

hello
hello
t1.buf == t2.buf ? yes
free Test
free Test

*** Error in `/home/yangju/test/c++/deepcopy': double free or corruption (fasttop): 0x0000000002541c20 ***

在默认复制构造函数中,t1.buf和t2.buf指向同一个地址,在析构的时候free了两次,发生问题。对于这样的问题。需要用深复制


深复制代码如下:

#include <iostream>
#include <string.h>

using namespace std;
class Test
{
public:
	char *buf;
	Test()
	{
		buf = NULL;
	}
	Test(const char *str)
	{
		buf = new char[strlen(str) + 1];
		strcpy(buf, str);
	};
	Test(Test &test)
	{
		cout << "copy create" << endl;
		buf = new char[strlen(test.buf) + 1];
		strcpy(buf, test.buf);
	}
	virtual ~Test()
	{
		if (buf != NULL)
		{
			cout << "free Test" << endl;
			delete buf;
			buf = NULL;
		}
	}
	
};

int main(int argc, char const *argv[])
{
	Test t1("hello");
	Test t2 = t1;
	cout << t1.buf << endl;
	cout << t2.buf << endl;

	cout << "t1.buf == t2.buf ? " << (t1.buf == t2.buf? "yes" : "no") << endl;

	return 0;
}

运行结果如下:

copy create
hello
hello
t1.buf == t2.buf ? no
free Test
free Test

[Finished in 0.4s]



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值