Skip to content

C.65 example code is wrong #1892

Closed
Closed
@ltimaginea

Description

@ltimaginea

C.65 Link: C.65: Make move assignment safe for self-assignment

image

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
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions