abraham_hilbert abraham_hilbert - 2 days ago 5
C++ Question

Do we need move and copy assignment

For a class

A
, can we use

A& operator=( A other ) { /* ... */ }


instead of

A& operator=( const A& other ) { /* ... */ }
A& operator=( const A&& other ) { /* ... */ }


without worsening performance or other negative effects?

Answer

Actually, you can implement copy-and-swap with

A& operator=( A other ) { swap(other, *this); return *this; }

for both copy and move assignment.

Except, above function can't be marked noexcept, move should be lightweight, cheap, it isn't required but it should be lightweight. Hence, move constructor/copy-assignment should be noexcept. without noexcept move constructor/assignment operator, move_if_noexcept can't be called when the container grows, the container will go back to copy.

Hence, the recommended way is:

A& operator=( const A&  other ) {
    if (std::addressof(other) != this) {
         A(other).swap(*this);
    }
    return *this;
}
A& operator=( A&& other ) noexcept { // note no const here
    // we don't check self assignment because
    // an object binds to an rvalue reference it is one of two things:
    //    - A temporary.
    //    - An object the caller wants you to believe is a temporary.
    swap(other); 
    return *this;
}
Comments