String Copy_on_write

#include <iostream>
using namespace std;


class String
{
public:
	String(const char* str = "")
		:_str(new char[strlen(str) + 5])
	{
		strcpy(_str+4 ,str);
		_GetRefCount(_str) = 1;
	}
		


	String(String& s)
		:_str(s._str)
	{
		++s._GetRefCount(_str);
	}
		


	
	String& operator=(const String& s)
	{
		if(this != &s)
		{
			this->_Release();
			//strcpy(_str,s._str);
			_str = s._str;
			++_GetRefCount(_str);
		}
		return *this;
	}
	
	char& operator[](size_t index)
	{
		if(_GetRefCount(_str) > 1)
		{
			_Release();
			char* tmp = new char[strlen(_str) + 5];
			strcpy(tmp + 4, _str);
			_GetRefCount(tmp) = 1;
			_str = tmp;
		}
		return _str[index];
	}
	
	~String()
	{
		_Release();
	}




private:
	int& _GetRefCount(char* str)
	{
		return *(int*)(str - 4);
	}


	void _Release()
	{
		if(--_GetRefCount(_str) == 0)
		{
			delete[] (_str-4);
		}
	}


friend ostream& operator<<(ostream& os, const String& s);


private:
	char* _str;
};




ostream& operator<<(ostream& os, const String& s)
{
	os<<"当前计数 "<<*(int*)(s._str - 4)<<endl;
	os<<s._str + 4;


	return os;
}


void Test1()
{
	String s1("sfdvfv");
	cout<<"s1 "<<s1<<endl;
	/*String s2(s1);*/
	//cout<<s2<<endl;
	String s3(s1);
	//s3 = s1;
	cout<<"s3 "<<s3<<endl;
	s3[2] = 'm';
	cout<<"s3 "<<s3<<endl;
	
}


int main()
{
	Test1();
 	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值