copy on write
- 写时拷贝是浅拷贝解决浅拷贝析构冲突的一种解决方案
- 相比较于深拷贝,写时浅拷贝占用空间少(相同内容不新开辟空间),复制效率高
几种写时拷贝方案比较
int _refCount (错误)
class String1
{
public:
String1(char* str)
:_refCount(1)
{
_str = (char*)malloc(strlen(str) + 1);
strcpy(_str, str);
}
String1(String1& s)
:_str(s._str), _refCount(++s._refCount)
{}
~String1()
{
_refCount--;
if (_refCount == 0)
free(_str);
}
String1& operator=(String1 s)
{
if (_str != s._str)
{
if (_refCount == 1)
free(_str);
_str = s._str;
_refCount = ++s._refCount;
}
}
private:
char* _str;
int _refCount;
};
用这种方法进行写时拷贝,对一个对象进行析构 _refCount– 时,访问不到其他相同对象的 _refCount , 只要进行拷贝或赋值,就会造成内存泄漏。
static int _refCount (错误)
class String2
{
char* _str;
static int _refCount;
};
int String2::_refCount = 0;
当出现不同的对象时,就会出现错误,_refCount 是唯一的。
int* _refCount (正确)
class String3
{
public:
String3(char* str)
{
_str = (char*)malloc(strlen(str) + 1);
strcpy(_str, str);
_refCount = new int(1);
}
String3(String3& s)
{
_str = (char*)malloc(strlen(s._str) + 1);
strcpy(_str, s._str);
_refCount = s._refCount;
(*_refCount)++;
}
String3& operator=(String3 s)
{
if (_str != s._str)
{
free(_str);
_str = s._str;
_refCount = s._refCount;
(*_refCount)++;
}
return *this;
}
~String3()
{
if (--(*_refCount) == 0)
{
free(_str);
delete _refCount;
}
}
private:
char* _str;
int* _refCount;
};
##隐含的 int 指针
在初始化 _str 时,在其前面多申请四字节空间,存放 int 型变量作计数器