写时拷贝方案分析 copy on write

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 型变量作计数器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值