您的位置:首页 > 运维架构

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

2015-03-23 10:06 239 查看
假设你建立一个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  }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: