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

后端 未结 3 537
攒了一身酷
攒了一身酷 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
      }
      
    0 讨论(0)
  • 2020-11-27 06:52

    The return type doesn't matter when you're just performing a single assignment in a statement like this:

    x = y;
    

    It starts to matter when you do this:

    if ((x = y)) {
    

    ... and really matters when you do this:

    x = y = z;
    

    That's why you return the current object: to allow chaining assignments with the correct associativity. It's a good general practice.

    0 讨论(0)
  • 2020-11-27 07:05

    The usual form returns a reference to the target object to allow assignment chaining. Otherwise, it wouldn't be possible to do:

    Foo a, b, c;
    // ...
    a = b = c;
    

    Still, keep in mind that getting right the assigment operator is tougher than it might seem.

    0 讨论(0)
提交回复
热议问题