String--引用计数写时拷贝

来源:互联网 发布:app软件操作说明书 编辑:程序博客网 时间:2024/05/17 15:19

写时拷贝
这里写图片描述

class String{public:    String(char* str = "")    {        _str = new char[strlen(str) + 1];        _refCountPtr = new int(1);        strcpy(_str, str);      }    ~String()    {        if (--*_refCountPtr = 0)        {            delete[] _str;            delete _refCountPtr;        }    }    String(String& s)        :_str(s._str)        , _refCountPtr(s._refCountPtr)    {        (*_refCountPtr)++;    }    String& operator = (const String& s)    {        if (_str != s._str)        {            if (--(*_refCountPtr) == 0)            {                delete[] _str;                delete _refCountPtr;            }            _str = s._str;            _refCountPtr = s._refCountPtr;            (*_refCountPtr)++;        }        return *this;    }    void CopyOnWrite(char ch)    {        if (*_refCountPtr > 1)        {            char* newStr = new char[_capacity + 1];            strcpy(newStr, _str);            (*_refCountPtr)--;            _str = newStr;            _refCountPtr = new int(1);        }    }    void PushBack(char ch)    {        CopyOnWrite(ch);        if (_size == _capacity)        {            Expand(2 * _capacity);        }        _str[_size++] = ch;        _str[_size] = '\0';    }    void Expand(size_t n)    {        if (n > _capacity)        {            _str =(char*) realloc(_str, n + 1);            assert(_str);            _capacity = n;        }    }    char& operator[](size_t pos)    {        CopyOnWrite(pos);        return _str[pos];    }    char operator[](size_t pos)const    {        return _str[pos];    }private:    char* _str;    size_t _size;    size_t _capacity;    int* _refCountPtr;};
原创粉丝点击