码迷,mamicode.com
首页 > 其他好文 > 详细

写时拷贝技术

时间:2016-09-06 23:32:37      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:写时拷贝技术

Copy On Write(COW):写时拷贝技术


一、什么是写时拷贝技术:

写时拷贝技术可以理解为“写的时候才去分配空间”,这实际上是一种拖延战术。

举个栗子:

技术分享

技术分享


二、写时拷贝技术原理:

  写时拷贝技术是通过"引用计数"实现的,在分配空间的时候多分配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;
};


本文出自 “11132019” 博客,转载请与作者联系!

写时拷贝技术

标签:写时拷贝技术

原文地址:http://11142019.blog.51cto.com/11132019/1846842

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