Item 11: Handle assignment to self inoperator=

在使用=是,我们可能遇到以下这种自己赋值给自己的情况

class Widget{---};
Widget w;
...
w = w;
  1. 假定我们对=有以下的实现
class Bitmap {...};
class Widget{
...
Widget& operator=(const Widget& rhs) {
	delete pb;
	pb = new Bitmap(*rhs.pb);
	return *this;
}
private:
	Bitmap *pb;
};

以上实现在遇到w = w自身赋值给自身(self-assignment-unsafe)的情况会出现错误,最后pb指向一个被delete的对象。

  1. 针对self-assignment-unsafe的问题,我们改进为如下
class Bitmap {...};
class Widget{
...
Widget& operator=(const Widget& rhs) {
	if (this == &rhs) return *thsi;
	delete pb;
	pb = new Bitmap(*rhs.pb);
	return *this;
}
private:
	Bitmap *pb;
};

以上实现解决了w = w的问题,但是依旧存在exception-unsafe的问题。因为在进行new 操作的时候可能会出现exception,这可能会导致pb指向一个delete的对象。

  1. 针对exception-unsafe的问题,我们改进如下
class Bitmap {...};
class Widget{
...
Widget& operator=(const Widget& rhs) {
	Bitmap *pOrig = pb;
	pb = new Bitmap(*rhs.pb);
	delete pOrig;
	return *this;
}
private:
	Bitmap *pb;
};
  1. 同样的为了消除self-assignment-unsafe和exception-unsafe的问题,我们可以使用copy and swap的方法
class Bitmap {...};
class Widget{
...
void swap(Widget& rhs);
Widget& operator=(const Widget& rhs) {
	Widget temp(rhs);
	swap(temp);
	return *this;
}
// or
Widget& operator=(Widget rhs) {
	swap(rhs);
	return *this;
}
private:
	Bitmap *pb;
};

对于以上的实现,并没有进行传入的参数是否自身的判断,因为考虑到效率方面的问题,引入判断之后会带来分支,影响性能。并且在正常使用的情况下,一般都不会出现传入参数为自身的情况,所以以上为了性能,没有加入判断是否为自身的if语句。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值