Three methods are used to process "self-assignment" in operator =, and operator assignment

Source: Internet
Author: User

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;
}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.