Home > Article > Backend Development > Is the `if (this != &rhs)` Check Necessary in a Move Assignment Operator?
In standard copy assignment operators for classes, it's common practice to check if the assigned object is the same as the invoking object using if (this != &rhs) to avoid altering the invoking object. But, is this check necessary for the move assignment operator?
The move assignment operator, denoted by operator=(Class&&), is designed for efficiently transferring ownership of resources from one object to another. Unlike copy assignment, it avoids the need to create a new copy of the object.
Can this == &rhs?
The question arises whether this == &rhs can ever be true in a move assignment operator.
There are two scenarios when an object binds to an rvalue reference:
In the first case, because the object is a unique reference to a temporary object, this == &rhs is impossible. In the second case, it's the caller's responsibility to ensure that this != &rhs, making the check unnecessary.
The author argues that the if (this != &rhs) check is redundant because:
By omitting this check, performance can be improved in situations where objects are frequently moved from and assigned to themselves.
However, some argue that the this != &rhs check is still necessary to prevent self-move-assignment. They contend that allowing swap(x, x) as a valid operation could trigger this check.
The author concludes that:
Copy and Move Assignment Post-Conditions:
Self-Move-Assignment Implementation:
To achieve this, three possible implementations for the move assignment operator in a class like dumb_array are provided:
1. A check is performed to distinguish self-move-assignment, and the object is set to a valid state before proceeding.
2. The check in omitted, making self-move-assignment a no-op.
3. The swap(other) method is used, provided that the class doesn't hold resources that should be immediately released.
The author stresses that the best implementation depends on the specific class design, hardware characteristics, and performance requirements.
In cases where the class doesn't manage memory directly, it suggests using operator=(Class&&) = default; to achieve the highest performance with basic exception safety.
The above is the detailed content of Is the `if (this != &rhs)` Check Necessary in a Move Assignment Operator?. For more information, please follow other related articles on the PHP Chinese website!