写时拷贝技术

写时拷贝故名思意:是在写的时候(即改变字符串的时候)才会真正的开辟空间拷贝(深拷贝),如果只是对数据的读时,只会对数据进行浅拷贝

写时拷贝技术原理:

    写时拷贝技术是通过"引用计数"实现的,在分配空间的时候多分配4个字节,用来记录有多少个指针指向块空间,当有新的指针指向这块空间时,引用计数加一,当要释放这块空间时,引用计数减一(假装释放),直到引用计数减为0时才真的释放掉这块空间。当有的指针要改变这块空间的值时,再为这个指针分配自己的空间(注意这时引用计数的变化,旧的空间的引用计数减一,新分配的空间引用计数加一)

利用写时拷贝技术实现简单string类:


class String

{

public:

	String(const char *str = "")

		:_str(new char[strlen(str) + 1 + 4])

	{

		cout << "Sring()" << endl;

		_str += 4;                            //前4个字节用来存放引用计数

		GetCount() = 1;                       //引用计数的初始值设置成1

		strcpy(_str, str);

	}

 

	String(String& s)

		:_str(s._str)

	{

		cout << "Sring(String&)" << endl;

		GetCount()++;

	}

 

	String& operator=(String& s)

	{

		cout << "Sring& operator=" << endl;

 

		if (this != &s)

		{

			Release();

			_str = s._str;

			GetCount()++;

		}

		return *this;

	}

 

	~String()

	{

		cout << "~Sring()" << endl;

		Release();

	}

public:

	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);        //注意释放的时候还有 存放引用计数的4个字节

			_str = NULL;

		}

	}

private:

	char *_str;

};


  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值