假設你建立一個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 }class VintagePort : public Port
{
public:
VintagePort& operator=(const VintagePort& rhs)
{
if(this ! = &rhs)
{
nickname = rhs.nickname;
year = rhs.year;
Port::operator=(rhs);
}
return *this;
}
private:
char * nickname;
int year;
}