用3种方法在 operator= 中处理“自我赋值”

假设你建立一个class 用来保存一个指针指向一块动态分配的位图。

1 class Bitmap {......};
2 class Widget{
3    ...
4    private:
5       Bitmap* pb ;
6 };
1 Widget&  Widget::operator= (const Widget& rhs)
2 {
3    delete pb;
4    pb = new Bitmap(*rhs.pb);
5    return *this;
6 }

上面是一份不安全的 operator= 实现版本,因为 operator= 函数内的*this 和 rhs 有可能是同一个对象。欲阻止这种错误有三种方法。

方法一:传统的方法

1 Widget&  Widget::operator= (const Widget& rhs)
2  {
3    if( this == rhs ) return *this;
4     delete pb;
5     pb = new Bitmap(*rhs.pb);
6     return *this;
7  }

方法二:

1 Widget&  Widget::operator= (const Widget& rhs)
2  {
3      Bitmap* pOrig = pb ;
4    
5      pb = new Bitmap(*rhs.pb);
6      delete pOrig ;
7      return *this;
8  }

方法三:所谓的copy and swap 技术

1 Widget&  Widget::operator= (const Widget& rhs)
2  {
3       Widget temp( rhs ) ;
4       swap(temp);
5  
6       return *this;
7  }

转载于:https://www.cnblogs.com/csxcode/p/3856399.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值