c++ 写实拷贝实现demo

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vld.h> // 内存泄漏检测
using namespace std;

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

// 引用计数类,通过深拷贝来构造
// 同时提供Increase Decrease来管理引用计数
class StringRep
{
	friend class String;
	friend ostream& operator<<(ostream &out, const String &s);
public:
	StringRep(const char *s = ""):useCount(0)
	{
		if (s == NULL)
		{
			str = new char[1];
			str[0] = '\0';
		}
		else
		{
			str = new char[strlen(s) + 1];
			strcpy(str, s);
		}
	 }
	StringRep(const StringRep &s) :useCount(0)
	{
		str = new char[strlen(s.str) + 1];
		strcpy(str, s.str);
	}
	StringRep& operator=(const StringRep &s)
	{
		if (this != &s)
		{
			delete[]str;
			str = new char[strlen(s.str) + 1];
			strcpy(str, s.str);
		}
		return *this;
	}
	void Increase()
	{
		++useCount;
	}
	void Decrease()
	{
		if (--useCount == 0)
			// 如果引用计数为0,自杀行为delete会调用析构释放成员str
			// 同时释放自身对象StringRep new 出来的空间
			delete this; 
	}
	~StringRep()
	{
		if (str != NULL)
			delete[] str;
		str = NULL;
	}
private:
	char *str;
	int useCount; // 引用计数
};

// 应用类,通过浅拷贝来构造
// 成员数据位引用计数类对象指针
// 通过引用计数类对象的引用计数实现写时拷贝
class String
{
	friend ostream& operator<<(ostream &out, const String &s);
public:
	String(const char* str = "")
	{
		rep = new StringRep(str);
		rep->Increase();
	}
	String(const String &s)
	{
		rep = s.rep;
		rep->Increase();
	}
	String& operator=(const String &s)
	{
		if (this != &s)
		{
			rep->Decrease();
			rep = s.rep;
			rep->Increase();
		}
		return *this;
	}
	// 写时拷贝方法的实现,即有写的操作时实现深拷贝
	char& operator[](int pos)
	{
		// 引用计数大于1,有多个对象共享空间
		if (rep->useCount > 1)
		{
			// 申请新的空间
			StringRep *newRep = new StringRep(rep->str);
			// 引用计数减少
			rep->Decrease();
			// 指向新的空间
			rep = newRep;
			// 新空间的引用计数增加
			rep->Increase();
		}
		return rep->str[pos];
	}
	~String()
	{
		rep->Decrease();
	}
private:
	StringRep *rep; // 引用计数类指针,通过引用计数类来管理数据成员
};

// 重载输出运算符
ostream& operator<<(ostream &out, const String &s)
{
	out << s.rep->str;
	return out;
}

int main()
{
	// s1 s2 s3 共享空间
	String s1("hello");
	String s2 = s1;
	String s3;
	s3 = s1;

	// 重载[]运算符,有写的操作,实现写时拷贝,即深拷贝
	s2[0] = 'H';

	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;

	system("pause");
	return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值