在前面的文章中我们总结了深拷贝的传统写法和现代写法,这次我们来总结一下写时拷贝。
当我们遇到需要大量拷贝构造,析构同样的空间的情况,传统写法和现代写法不断的开辟空间,析构空间,效率太低,这时,我们就可采用写时拷贝:当一个对象被拷贝构造多次,在不改变内容的情况下,多个对象共用同一个空间。如果某个对象要改变内容,就要另外开辟一块相同的空间,然后改变这个对象的_str指针,再进行写操作。
引用计数的写时拷贝是基于引用计数的浅拷贝
其原理如下
当refcount减小为一时才释放该块内存
其代码实现如下
#include<iostream>
#include<assert.h>
using namespace std;
class String
{
public:
String(const char* str="")
:_str(new char[strlen(str)+1])
,_refCount(new int(1))
{
strcpy(_str,str);
}
String(const string&s)
{
_str = s._str;
_refCount = s._refCount;
++(*_refCount);
}
String & operator = (const String &s)
{
if(_str ! = s._str)
{
Release();
_str = s._str;
_refCount = s._refCount;
++(*_refCount);
}
return *this;
}
~String()
{
Release();
}
void Release()
{
if(--(*_refCount == 0))
{
delete[]_str;
delete[]_refCount;
}
}
char & operator[](_size_t pos)
{
CopyOnWrite();
return _str[pos];
}
void CopyOnWrite()
{
if(*_refCount > 1)
{
char* tmp = new char[strlen(_str)+1];
strcpy(tmp,_str)
--(*_refCount);
_str = tmp;
_refCount = new int[1];
}
}
private:
char*_str;
int*_refCount;
};
上面这种方法refCount占用了一个空间,指向的内容开辟了一个空间,我们可以对这个程序进行优化
我们可以开辟一个空间让这块空间的前四个字节存放refCount,后面存放指向的内容
具体代码实现如下
#include<iostream>
#include<assert.h>
using namespace std;
#pragma warning(disable:4996)
class String
{
public:
String(const char* str="")
:_str(new char[strlen(str)+5])
{
*((int*)_str) = 1;
_str+=4;
strcpy(_str,str);
}
String(const String&S)
:_str(S._str)
{
++GetRefCount();
}
String & operator = (const String &S)
{
if(_str!=S._str)
{
if(--GetRefCount() == 0)
{
delete(_str-4);
}
_str = S._str;
GetRefCount()++;
}
return *this;
}
~String()
{
if(--GetRefCount()== 0)
{
cout << "delete" << endl;
delete(_str-4);
}
}
int&GetRefCount()
{
return(*(int*)(_str-4));
}
private:
char*_str;
};