码迷,mamicode.com
首页 > 编程语言 > 详细

【c++】浅拷贝与深拷贝

时间:2015-05-15 17:41:50      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:深拷贝   浅拷贝   

// 浅拷贝与深拷贝

// 像这样的浅拷贝会导致程序崩溃,因为同一个空间被释放了两次
#include <iostream>
#include <string.h>
using namespace std;

class S_Copy;
ostream& operator<<(ostream& out, const S_Copy &s);

class S_Copy
{
	friend ostream& operator<<(ostream& out, const S_Copy &s);
	public:
		S_Copy(const char *str = "")
		{
			p = new char[strlen(str) + 1];
			strcpy(p, str);
		}
		~S_Copy()
		{
			delete[]p;
		}
	private:
		char *p;
};

ostream& operator<<(ostream& out, const S_Copy &s)
{
	out << s.p;
	return out;
}

int main()
{
	S_Copy s1("hello");
	S_Copy s2(s1);
	cout << s2 << endl;
	return 0;
}

// 如图,两个对象里的指针指向了同一个地址

技术分享




// 深拷贝
#include <iostream>
#include <string.h>
using namespace std;

class S_Copy;
ostream& operator<<(ostream& out, const S_Copy &s);

class S_Copy
{
	friend ostream& operator<<(ostream& out, const S_Copy &s);
public:
	S_Copy(const char *str = "")
	{
		p = new char[strlen(str) + 1];
		strcpy(p, str);
	}
	// 重写拷贝构造函数,也开辟出一块空间
	S_Copy(const S_Copy &s)
	{
		p = new char[strlen(s.p) + 1];
		strcpy(p, s.p);
	}
	~S_Copy()
	{
		delete[]p;
	}
private:
	char *p;
};

ostream& operator<<(ostream& out, const S_Copy &s)
{
	out << s.p;
	return out;
}

int main()
{
	S_Copy s1("hello");
	S_Copy s2(s1);
	cout << s2 << endl;
	return 0;
}

技术分享

【c++】浅拷贝与深拷贝

标签:深拷贝   浅拷贝   

原文地址:http://blog.csdn.net/zhaoyaqian552/article/details/45747183

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!