Three methods are used to process "self-assignment" in operator =, and operator assignment
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 }
In C ++, how does a derived class reload operator = to assign a value to the base class without using protected?
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;
}