rmaicle

Programming is an endless loop; it's either you break or exit.

Licensed under a Creative Commons Attribution-ShareAlike 4.0 International License (CC BY-SA).
You are free to copy, reproduce, distribute, display, and make adaptations but you must provide proper attribution. Visit https://creativecommons.org/ or send an email to info@creativecommons.org for more information about the License.

Safe Copy Assignment

Date: 2015-12-20 20:58:30 +0000

How to write a C++ copy assignment that provides strong exception guarantee.

Exception-Safe Coding, Jon Kalb

From the talk of Jon Kalb on C++Now! 2012 with the same title. You can acquire the slides here.

1
2
3
4
5
6
7
T& T::operator= (T const &rhs) {
    if (this != &x) {
        this->~T();             // destroy in place
        new (this) T(rhs)       // construct in place using copy constructor
    }
    return *this;
}

Copy and Swap Idiom

See the Copy and Swap Idiom discussed here in More C++ Idioms.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
T& T::operator= (T rhs) {       // assignment using copy construction
    rhs.swap(*this);            // non-throwing swap
    return *this;
}

void T::swap(T &o) {
    using std::swap;            // enable ADL (may not be necessary, but good practice)
                                // swap(a.member, b.member);
                                // ...
}

namespace std {
    template <>                 // Full specialization of std::swap() for type T
    void swap (T &a, T &b) {
        a.swap(b);              // Uses T::swap()
    }
}; //_ namespace std
What is the copy-and-swap idiom? from StackOverflow

Here is the link to an answer to the StackOverflow question. The author suggests the following solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class T {
    T& T::operator= (T rhs)
    {
        swap(*this, rhs);
        return *this;
    }

    friend void swap(T &a, T &b) {
        using std::swap;                // enable ADL
        // swap the members
        swap(a.one, b.one);
        swap(a.two, b.two);
    }
};

As a consequence, a move constructor in C++11 can be easily written as:

1
2
3
T::T (T &&other) : T() {
    swap(*this, other);
}
ADL and swap Articles

Articles related to Argument Dependent Lookup (ADL) for user-defined type swap function:

Move Assignment and swap

Here is a short article by Scott Meyers related to move assignment using swap function.

More and more, I bump into people who, by default, want to implement move assignment in terms of swap. This disturbs me…

The Drawbacks of Implementing Move Assignment in Terms of Swap

  •  copy assignment