Skip to main content

副本构造器(重载=,赋值运算符)

当一个类中包含指针成员,强烈建议使用副本构造器(重载=),以免发生越界或内存泄漏

例如:

/*假设有class Test,内有一个int* ptr*/
  class Test a;
  a.ptr=new int(3);
  b=a;   //此时b中的ptr也指向a中ptr的地址
  delete a.ptr;
  cout<<*b.ptr;   //报错,越界访问

副本构造器:

class Test{
  public:
    int* ptr;

    ~Test(){
      delete this->ptr;
    }

    Test &operator=(const Test &b){
      if(this!=b){   //赋值号左右两边相同时不做处理
        delete this->ptr;
        this->ptr=new int(*b.ptr);
      }
      return *this;
    }
};