引用計數寫時拷貝

拷貝可以概括性的分爲以下幾類
這裏寫圖片描述
1 s1和s2分別有它們自己的值,我們需要將s1的對應的空間釋放掉然後賦給其s2的值
2 s1和s2分別有它們自己的值,但是s1還有其他別名,我們需要引入計數,爲了防止其在析構時程序崩潰(多次釋放同一塊內存空間)。如圖
3 s1和s2對應同一塊內存空間,那麼我們就不需要賦值了。

//構造函數
String(const char* ptr = " ")  
    {  
        if(ptr == NULL)  
        {  
            _ptr = new char[1];  
            _pcount = 1;  
            *_ptr = '\0';  
        }  
        else  
        {  
            _pcount = 1;  
            _ptr = new char[strlen(ptr)+1];  
            strcpy(_ptr,ptr);  
        }  
    }
//賦值運算符重載 
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;
}
//拷貝構造
String(String& s)  
        :_ptr(s._ptr)  
        ,_pcount(s._pcount)  
    {  
        _pcount++;  
    }  
 //析構函數  
~String()  
{  
 if((0 == --_pcount) && _ptr!= NULL)  
  {  
    delete[]_ptr;  
    //delete _pcount;  
    _ptr = NULL;  
   }  
 }  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章