寫時拷貝技術

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


1、什麼是寫時拷貝技術:this

寫時拷貝技術能夠理解爲「寫的時候纔去分配空間」,這其實是一種拖延戰術。url

舉個栗子:
spa

spacer.gif


2、寫時拷貝技術原理:指針

  寫時拷貝技術是經過"引用計數"實現的,在分配空間的時候多分配4個字節,用來記錄有多少個指針指向塊空間,當有新的指針指向這塊空間時,引用計數加一,當要釋放這塊空間時,引用計數減一(僞裝釋放),直到引用計數減爲0時才真的釋放掉這塊空間。當有的指針要改變這塊空間的值時,再爲這個指針分配本身的空間(注意這時引用計數的變化,舊的空間的引用計數減一,新分配的空間引用計數加一)。string


3、利用寫時拷貝技術實現簡單string類:it

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;
};
相關文章
相關標籤/搜索