effective c++条款11 在operator=中处理“自我赋值”

在实现operator=时考虑自我赋值是必要的就像 x=y ,我们不知道变量x与y代表的值是否为同一个值(把x和y说成是一个指针更恰当一点)。如下

class bitmap{};
class Widget{
public:
    Widget& operator=(const Widget& rhn);
private:
    bitmap *pb; //定义一个指针指向对分配的空间
}

第一版赋值函数:

Widget& Widget::operator=(const Widget& rhs)
{
    delete pb;
    pb = new bitmap(*rhs.pb);
    return this;
}

这般函数的pb在使用前清理掉之前的pb指向,在接受一个new出来的新对象,看着很顺理成章,但当 this 与函数的参数rhs相等时pb = new bitmap(*rhs.pb);会执行出错,因为我们已经把*rhs.pb delete了。

第二版赋值函数:

Widget& Widget::operator=(const Widget& rhs)
{
    if(*this == rhs)
return *this; delete pb; pb = new bitmap(*rhs.pb) return *this; }

这个版本的赋值函数基本上是可以接受的,但不见的是安全的,因为当new产生异常时pb依然是个不确定的指针。

第三个版本:

idget& Widget::operator=(const Widget& rhn)
{
    bitmap *pOrig = pb;
    pb = new bitmap(*rhn.pb);
    delete pOrig;
    return this;
}

 这个函数在开始时用pOrig记录了pb,当new没有异常时我们在把Pb原来的指向空间释放掉,从而提高了安全性。

实现赋值函数还有另外一个思想,即copy and swap技术

class Widget {

void swap(const Widget& rhs);


}

Widget& Widget::operator=(const Widget& rhs)    
{
    Widget temp(rhs);  //防止改变rhs
    swap(temp);
    return *this;

}

当然我们也可以by value 传递参数

Widget& Widget::operator=(const Widget rhs) //按值传递是实参的一个copy   
{
    swap(temp);
    return *this;

}

copy and swap技术的缺点是巧妙的运用swap丧失了代码的清晰性,然而将“copy动作”移动到函数参数的构造阶段令编译器有时生成高效的代码..

原文地址:https://www.cnblogs.com/onlycxue/p/3070222.html