String的浅拷贝

来源:互联网 发布:三国杀风火林山淘宝 编辑:程序博客网 时间:2024/04/29 08:10
class String{public:    String(const char* str="")        :_str(new char[strlen(str) + 5])    {        cout << "String()" << endl;        _str += 4;        _GetRefCount(_str) = 1;        strcpy(_str, str);    }    String(const String& s)        :_str(s._str)    {        ++_GetRefCount(_str);    }    ~String()    {        cout << "~String()" << endl;        _Release();    }    String& operator=(const String& s)    {        if (_str != s._str)        {            _Release();            _str = s._str;            ++_GetRefCount(_str);        }        return *this;    }    char& operator[](int index)//不写现代写法    {        if (_GetRefCount(_str) > 1)        {            char* tmp = new char[strlen(_str) + 5];            tmp += 4;            _GetRefCount(tmp) = 1;            strcpy(tmp, _str);            --_GetRefCount(_str);            _str = tmp;        }        return _str[index];    }    int GetRefCount()    {        return _GetRefCount(_str);    }    char* C_str()    {        return _str;    }private:    int& _GetRefCount(char* str)    {        return *(int *)(str - 4);    }    void _Release()    {        if (--_GetRefCount(_str) == 0)        {            delete[] (_str-4);//注意指针的位置        }    }private:    char* _str;}


0 0
原创粉丝点击