Why should the assignment operator return a reference to the object?

后端 未结 3 574
攒了一身酷
攒了一身酷 2020-11-27 06:38

I\'m doing some revision of my C++, and I\'m dealing with operator overloading at the minute, specifically the \"=\"(assignment) operator. I was looking online and came acro

3条回答
  •  甜味超标
    2020-11-27 06:51

    Your assignment operator should always do these three things:

    1. Take a const-reference input (const MyClass &rhs) as the right hand side of the assignment. The reason for this should be obvious, since we don't want to accidentally change that value; we only want to change what's on the left hand side.

    2. Always return a reference to the newly altered left hand side, return *this. This is to allow operator chaining, e.g. a = b = c;.

    3. Always check for self assignment (this == &rhs). This is especially important when your class does its own memory allocation.

      MyClass& MyClass::operator=(const MyClass &rhs) {
          // Check for self-assignment!
          if (this == &rhs) // Same object?
              return *this; // Yes, so skip assignment, and just return *this.
      
          ... // Deallocate, allocate new space, copy values, etc...
      
          return *this; //Return self
      }
      

提交回复
热议问题