Effective C++第二章-构造,析构,赋值 -2

operator=返回一个reference to * this

协议:赋值操作符必须返回一个reference指向操作符(&)的左侧实参。

class Widget{
public:
...
  Widget& operator=(const Widget& rhs)
  {
    ...
    return* this;
  }
};
  • 该协议适用于所有赋值相关运算
  • 只是协议,如果不遵循代码一样可通过编译
  • 所有内置类型和标准程序库提供的类型如string,vector,complex,trl::shared_ptr共同遵守该协议。

“自我赋值”

自我赋值有时并不明显,由别名引起。

a[i]=a[j];//潜在的自我赋值i=j
*px=*py;//潜在的自我赋值,px和py指向同一变量;

可能会导致在停止使用资源之前意外释放了它,例如:

class Bitmap{...};  
class Wiget  
{  
    ...  
private:  
    Bitmap* pb;  
}  
Wiget::operator= (const Wiget& rhs)  
{  
    delete pb;  //停止使用当前的bitmap。如果this和rhs指向同一对象会出问题
    pb = new Bitmap(*rhs.pb);//使用rhs的bitmap的副本。  
    return *this;   
}  

可以通过“证同”或者“copy and swap”解决该问题。

//证同
Wiget::operator = (const Wiget& rhs)  
{  
    if(this == &rhs)return *this;   //证同测试,如果是自我赋值,就不作任何事   
    delete pb;    
    pb = new Bitmap(*rhs.pb);  
    return *this;   
}  
//copy and swap
Widget& Widget::operator = (const Widget& rhs)  
{  
    Bitmap* pOrig = pb; //记住原先的pb  
    pb = new Bitmap(*rhs.pb);//令pb指向*pb的一个副件  
    delete pOrig; //删除原先的pb  
    return *this;   
}  

复制对象时勿忘每一个成分(派生类继承基类的成分)

  • 如果自己声明coping函数(copy构造函数和copy assignment操作符),而不使用编译器缺省实现的某些行为。会导致编译器在你的实现代码几乎必然出错时却不告诉你,因此必须小心地复制base class成分。

  • 如果你为类添加一个成员变量,你必须同时修改coping函数,也需要修改class的所有构造函数以及任何非标准形式的operator=

  • 如果派生类的copy构造函数并没有指定实参传给其base class构造函数,则派生类对象的基类成分会被不带实参之基类构造函数初始化

    //错误示范--没有指定实参传给其base class构造函数
    class PriorityCustomer:public Customer  
    {  
    public:  
      PriorityCustomer(const PriorityCustomer& rhs);  
      PriorityCustomer& operator=(const PriorityCustomer& rhs);  
      ...  
    private:  
      int priority;  
    };
    //纠正示范--指定实参传给其base class构造函数
    PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs)  
    :Customer(rhs),priority(rhs.priority)  //调用base classcopy构造函数  
    {}  
    
    PriorityCustomer& PriorityCustomer::operator = (const PriorityCustomer& rhs)  
    {  
      Customer::operator=(rhs);  //对base class成分进行赋值动作  
      priority=rhs.priority;  
      return *this;  
    }  

PS:如果copy构造函数和copy assignment操作符有相近的代码,可以建立一个新的成员函数给两者调用。该函数一般是private。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值