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/archive/2013/05/09/3070222.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/87748

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午11:15
下一篇 2023年2月9日 下午11:15

相关推荐