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 ??
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 ??
Copyright © 2021 Jogjafile Inc.
Usually...
Suppose your class holds a pointer to some buffer that it allocates. Now, in a naive move-assignment operator, you would:
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.