拷贝构造函数/赋值构造函数

1、拷贝构造函数
拷贝构造函数形参类型必须为对象类型
  • A( A other )  { }            将导致无穷递归,编译不会出错,但是运行时,会把内存耗尽
  • A( const A& other) { }    不会产生内存耗尽
2、赋值构造函数----重载赋值操作符
标准实现如下:
class String
{
private:
     char* ptr;
public:
     //....
      String&  String::operator=(const String &str)      
      {
             if(this  == &str)
             {
                    return *this;
              }
              delete []ptr;
              ptr = null;
              ptr = new[strlen(str.ptr) + 1];   //strlen(字符串)不包括最后的\0,但是sizeof(字符串)包括后面的\0。
              strcpy(ptr, str.ptr);
              return *this;
      }
      //.....
}

关注五点:
  • 形参--by const  reference
  • 返回值为引用类型
  • 先判断是否是自赋值,不判断的话,会导致删除自身
  • 记住delete,防止内存泄漏
  • 深拷贝
考虑异常情况:在new分配内存空间失败情况下,保证对象的内部状态不改变
String& String::operator=(const String &str)
{
     if(&str != this)  
     {
          String tempStr(Str);
          char* pTemp = tempStr.ptr;
          tempStr.ptr = this->ptr;
          this->ptr = pTemp;
     }
     return *this;
}

你可能感兴趣的:(拷贝构造函数/赋值构造函数)