标签:
Item 11-在operator = 中处理"自我赋值"(Handle assignment to self in operator = )
"自我赋值"发生在对象被赋值个自己:
Ex1:
class Widget{...}; Widget w; ... w=w; //赋值给自己
class Bitmap{...}; class Widget { ...; private: Bitmap* pb; //指针,指向一个从heap分配而得的对象 };
Widget & Widget::operator = (const Widget& rhs) //一份不安全的operator = 实现版本 { delete pb; pb = new Bitmap(* rhs.pb) //使用rhs’s bitmap的副本 return *this; }
解决方案
1、operator = 最前面的一个"证同测试"(identity test)
Widget& Widget::operator = (const Widget& rhs) { if(this = &rhs) return *this // identity test delete pb; pb = new Bitmap(* rhs.pb) return *this; }
Widget& Widget::operator = (const Widget& rhs) { Bitmap* pOrig = pb; //记住原先的pb pb = new Bitmap(*rhs.pb); //令pb指向*pb的一个复件 delete pOrig; //删除原先的pb return *this; }
class Widget { ... void swap(Widget& rhs); //交换*this的rhs的数据 }; Widget& Widget::operator = (const Widget& rhs) { Widget temp(rhs); //为rhs数据制作一份复件 swap(temp); //将*this数据和上述复件的数据交换 return *this; }
确保当对象自我赋值时operator = 有良好行为。其中技术包括比较"来源对象"和"目标对象"的地址,精心周到的语句顺序,以及copy and swap。
确定任何函数如果操作一个以上的对象,而其中多个对象是同一个对象时,其行为仍然正确。
Effective C++ Item 11-在operator = 中处理"自我赋值"
标签:
原文地址:http://blog.csdn.net/u011391629/article/details/52161029