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 ??
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.
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.
std::vector to itself will remove its content (both libc++ and stdlibc++).y to x you expect x to have the same value as y had before (move or no move).y, it is not unexpected that its content is empty. So there are contradicting expectations in this case. That's why I ask, where does this mean actually a problem?. For example, "moving" swap still works (tmp = move(a); a = move(b); b = move(tmp)). Is there any algorithm, where this behavior (data-loss) causes a problem? It must have a reason that the standard doesn't require data be kept in this case.x should be equal to what y was before the assignment. And it is violated. Which usually doesn't cause any problems (I haven't found any case yet). But it still can be unexpected.
Type a; a = std::move(a);Technically, it's not required at all anytime, though can be very helpful in Rule-of-[35]-subject classes, to get consistency for a small price.int*and implement move assignment for it without checking for self-assignment. How bug-free is it?assert(this!=&rhs)and see what happens. Otherwise you can specify it has a default semantic, like resetting the object.