c++ string 浅拷贝 深拷贝

c++ string 浅拷贝 深拷贝

转载 https://blog.csdn.net/hansionz/article/details/83993963#1_303

  • 传统写法
/**
 *  模拟实现string类的构造、拷贝构造、赋值运算符重载
 *  
*/
class String
{
public:
 //构造函数
 String(char* str = "")
 {
  // 构造string类对象时,如果传递nullptr指针,认为程序非法,此处断言
  if (str == nullptr)
  {
   assert(false);
   return;
  }
  _str = new char[strlen(str) + 1];
  strcpy(_str, str);
 }
 //析构函数
 ~String()
 {
  if (_str)
  {
   delete[] _str;
   _str = nullptr;
  }
 }
 //拷贝构造(深拷贝)
 String(const String& s)
  :_str(new char[strlen(s._str) + 1])
 {
  strcpy(_str, s._str);
 }
 //赋值运算符重载
 String& operator=(const String& s)
 {
  if (this != &s)//防止自己给自己赋值
  {
   delete[] this->_str; // s2的空间比当前空间大,所以要先释放s1既当前对象,
                        //然后在开辟和s2一样大的空间进行拷贝
   _str = new char[strlen(s._str) + 1];
   strcpy(_str, s._str);
  }
  return *this;//连续赋值
 }
private:
 char* _str;
};
  • 现代写法
/**
 *  模拟实现string类的构造、拷贝构造、赋值运算符重载
 *  
*/
cl
class String
{
public:
 //构造函数
 String(char* str = "")
 {
  // 构造string类对象时,如果传递nullptr指针,认为程序非法,此处断言
  if (str == nullptr)
  {
   assert(false);
   return;
  }
  _str = new char[strlen(str) + 1];
  strcpy(_str, str);
 }
 //析构函数
 ~String()
 {
  if (_str)
  {
   delete[] _str;
   _str = nullptr;
  }
 }
 //拷贝构造(深拷贝)
 String(const String& s)
  :_str(nullptr)
 {
  String tmp(s._str);//复用构造函数
  swap(_str, tmp._str);
 }
 //赋值运算符重载
 String& operator=(String s) //传值过程中存在一份拷贝构造
 {
  swap(_str, s._str);
  return *this;
 }
private:
 char* _str;
};

猜你喜欢

转载自blog.csdn.net/m0_37329910/article/details/88706136