Is a self-assignment check really required while implementing move assignment operator for a class?

1.6k Views Asked by At
Type &Type::operator=(Type &&rhs)
{
if(this == &rhs) //is there any need of self-assignment . 
returh *this ;
}
...
}

//since it will be called on r-value so why self-assignment ??

1

There are 1 best solutions below

6
On

Usually...

Suppose your class holds a pointer to some buffer that it allocates. Now, in a naive move-assignment operator, you would:

  • Free your own buffer
  • Assign the other object's buffer pointer to your buffer pointer
  • Assign null to the other object's buffer pointer, and perhaps set its size to 0

This will not make you dereference a null pointer, but - you've just lost all data in your buffer, which is likely not what you wanted, nor what the user expected.

... but not always

There is a (narrow) exception to the rule above: The case of your move-assignment operator being 'idempotent' for self-assignment. For example, if your assignment operator only involves assignment of the members - then it's safe to self-assign just like a regular assignment (trusting that the members' self-assignment implementations are valid). Nothing will be changed or lost.

This exception to the rule is indeed narrow, since the above is mostly true for the example I gave - in which case you would use the default move-assignment operator. Still, just because you don't find this check in someone's code does not mean there's a bug.