详解C++中String类模拟实现以及深拷贝浅拷贝

2020-01-06 17:43:53王振洲

 pCount来标记一块空间被几个对象占用,当只有一个对象占用如果进行析构便可释放空间,否则只对*pCount--。


//浅拷贝优化--带有计数版本的String类,用指针指向计数的空间 
class String { 
public: 
  String(const char* s = "") : _pCount(new int(1)) 
  { 
    if (NULL == s) { 
      _pStr = new char[1]; 
      *_pStr = ''; 
    } 
    else { 
      _pStr = new char[strlen(s) + 1]; 
      strcpy(_pStr, s); 
    } 
  } 
  String(const String& s) 
  { 
    _pStr = s._pStr; 
    _pCount = s._pCount; 
    (*_pCount)++; 
  } 
  String& operator=(const String& s) 
  { 
    if (this != &s) { 
      if (--(*_pCount) == 0) { 
        delete[] _pStr; 
        delete _pCount; 
      } 
      _pStr = s._pStr; 
      _pCount = s._pCount; 
      (*_pCount)++; 
    } 
    return *this; 
  } 
  ~String() 
  { 
    if (NULL != _pStr && --(*_pCount) == 0) { 
      delete[] _pStr; 
      delete _pCount; 
    } 
    _pCount = NULL; 
    _pStr = NULL; 
  } 
 
private: 
  char* _pStr; 
  int* _pCount; 
}; 

最后再给出一种深拷贝的简洁版本,通过调用swap来简化操作,代码如下:


//深拷贝的简洁写法 
class String { 
public: 
  String(const char* s = "") 
  { 
    if (NULL == s) { 
      _pStr = new char[1]; 
      *_pStr = ''; 
    } 
    else { 
      _pStr = new char[strlen(s) + 1]; 
      strcpy(_pStr, s); 
    } 
  } 
  String(String& s) :_pStr(NULL)//必须对_pStr初始化,防止释放随机值的空间 
  { 
    String temp(s._pStr); 
    swap(_pStr, temp._pStr); 
  } 
  String& operator=(String& s) 
  { 
    if (this != &s) {  
      swap(_pStr, s._pStr); 
    } 
    return *this; 
  } 
  ~String() 
  { 
    if (NULL != _pStr) { 
      delete[] _pStr; 
      _pStr = NULL; 
    } 
  } 
private: 
  char* _pStr; 
}; 


如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


注:相关教程知识阅读请移步到C++教程频道。