首页 > 其他 > 详细

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

时间:2014-07-21 08:39:22      阅读:259      评论:0      收藏:0      [点我收藏+]

假设你建立一个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  }

用3种方法在 operator= 中处理“自我赋值”,布布扣,bubuko.com

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

原文:http://www.cnblogs.com/csxcode/p/3856399.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!