Closed
Description
C.65 Link: C.65: Make move assignment safe for self-assignment
If someone move-assigns an object to itself, line delete ptr;
deletes both this->ptr
and other.ptr
(i.e., temp
) since *this
and other
are the same object. Finally, *this
is no longer a valid object.
In my opinion, the move assignment operator must have a self-assignment test. The correct example code is as follows:
// move assignment operator
HasPtr& HasPtr::operator=(HasPtr&& other) noexcept
{
// direct test for self-assignment
if (this == &other) return *this;
// move from other.ptr to this->ptr
T* temp = other.ptr;
other.ptr = nullptr;
delete ptr;
ptr = temp;
return *this;
}
Metadata
Metadata
Assignees
Labels
No labels