Suppose you create a class to save a pointer pointing to a dynamically allocated bitmap.
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 }
The above is an insecure operator = implementation version, because operator = * This and RHS in the function may be the same object. There are three methods to prevent such errors.
Method 1: Traditional Methods
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 }
Method 2:
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 }
Method 3: the so-called copy and swap Technology
1 Widget& Widget::operator= (const Widget& rhs)2 {3 Widget temp( rhs ) ;4 swap(temp);5 6 return *this;7 }