Operator = handle self-assignment

Source: Internet
Author: User

Many times, we write operator = functions of the class (for example, when the class contains pointers ).
Consider the following class:
class Widget {public:  Widget(int x=0): val(new int(x)) {}  ~Widget() { delete val; }  Widget(const Widget &rhs): val(new int(*rhs.val)) {}  //operator =  Widget& operator=(const Widget &rhs);  void print() const { cout << *val << endl; }private:  int *val;};

Incorrect version: the following code is insecure when you assign values to yourself. If * This and RHS are the same object, the first statement is delete val;
Not only does the Val of the current object be deleted, but the Val of RHS is also deleted. RHS. Val points to a deleted int, which inevitably produces a strange problem.
/** wrong version * not-safe when self-assignment occurs. */Widget& Widget::operator=(const Widget &rhs) {  delete val;  val = new int(*rhs.val);  return *this;}

Improved Version 1: the traditional way to prevent such errors is to add an identity test ).
Widget& Widget::operator=(const Widget &rhs) {  if(this == &rhs) return;  delete val;  val = new int(*rhs.val);  return *this;}

However, although the above practices are self-replication secure, they do not have exceptional security.
If the new int throws an exception, this-> Val points to a deleted Int.
Improved Version 2: Both exception security and self-replication Security
Widget& Widget::operator=(const Widget &rhs) {  int *pOld = val;  val = new int(*rhs.val);  delete pOld;  return *this;}

Improved Version 3: Copy and swap Technology
Widget& Widget::operator=(const Widget &rhs) {  Widget temp(rhs);  swap(temp);  return *this;}

Improved Version 4: Copy and swap by passing values
Widget& Widget::operator=(Widget rhs) { //yes, copy by value  swap(rhs);  return *this;}

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.