寫時拷貝技術

Copy On Write(COW):寫時拷貝技術


一、什麼是寫時拷貝技術:

寫時拷貝技術可以理解爲“寫的時候纔去分配空間”,這實際上是一種拖延戰術。

舉個栗子:

spacer.gif


二、寫時拷貝技術原理:

  寫時拷貝技術是通過"引用計數"實現的,在分配空間的時候多分配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;
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章