写时拷贝

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;

#include<string.h>
#include<windows.h>

#if 0
class String
{
public:
	String(const char* str = "")
		:_str(new char[strlen(str) + 1])
		,_retCount(new int(1))
	{
		strcpy(_str, str);
	}

	String(const String& s)
		:_str(s._str)
		,_retCount(s._retCount)
	{
		_retCount[0]++;
	}

	String& operator=(const String& s)
	{
		if (this != &s)
		{
			if (--_retCount[0] == 0)
			{
				delete[] _str;
				delete[] _retCount;
			}
			_str = s._str;
			_retCount = s._retCount;
			++_retCount[0];
		}

		return *this;
	}

	~String()
	{
		if (--_retCount[0] == 0)
		{
			delete[] _str;
			delete[] _retCount;
		}
	}

private:
	char* _str;
	int* _retCount;
};
#endif

//上面是是每个对象对应一个整型空间(即_refCount)存放指向这块空间的对象个数
//优化:不引用_refCount,但每次给_str开辟空间的时候,多开辟四个字节,用来记录指向此空间的对象个数,
//规定用开头那四个字节来计数。

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

	String(String& s)
		:_str(s._str)
	{
		cout << "String(String& s)" << endl;
		GetCount()++;
	}

	String& operator=(String& s)
	{
		cout << "String& operator=" << endl;
		if (this != &s)
		{
			Release();
			_str = s._str;
			GetCount()++;
		}
		return *this;
	}

	~String()
	{
		cout << "~String()" << endl;
		Release();
	}
		
	char& operator[](size_t index)
	{
		if (GetCount() == 1)  //如果计数器为1 则直接返回
			return _str[index];

		GetCount()--;
		char* tmp = _str;
		_str = new char[strlen(tmp) + 1 + 4];
		_str += 4;
		strcpy(_str, tmp);
		GetCount() = 1;

		return _str[index];
	}

private:
	int& GetCount()
	{
		return *(int*)(_str - 4);
	}
	void Release()
	{
		if (--GetCount() == 0)
		{
			cout << "释放" << endl;
			delete[](_str - 4);
			_str = NULL;
		}
	}
private:
	char* _str;
};

int main()
{
	String s1 = "hello world";
	String s2 = s1;
	cout << s1[3] << s2[4] << endl;
	/*
	int begin = (int)GetTickCount64();
	for (int i = 0; i < 1000; i++)
	{
		String s2 = s1;
	}
	int end = (int)GetTickCount64();
	cout << "run time:" << end - begin << endl;
	*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值