c++operator-overloadingcopy-constructorassignment-operatorcopy-and-swap

Why do we use copy and swap when using assignment operator?


I have a question about assignment operator when using copy-and-swap method.

String & operator = (String s) // the pass-by-value parameter serves as a temporary
{
   s.swap (*this); // Non-throwing swap
   return *this;
}// Old resources released when destructor of s is called.

Let's suppose we have a good copy constructor which deep-copy all the pointers and dynamic allocated variables.

Then, what's the difference between above code and below code?

String & operator = (String s) // the pass-by-value parameter serves as a temporary
{
   return s;
}

Since, we have a good copy constructor, I think another object, s, is created inside the operator= function. So, what's the point of using non-throwing swap function?


Solution

  • The main difference is that the 2nd operator= doesn't change the current object (i.e. *this) at all.

    String a, b;
    b = a; // b is not changed at all
    

    And note the 2nd operator= is returning s (which will be destroyed when get out of the function) by reference, so it'll be just a dangled reference.


    To be more general, we use copy & swap idiom to provide strong exception safety guarantee, which is something like commit-or-rollback semantics; If an operation terminates because of an exception, program state will remain unchanged.

    String & operator = (String s) // Copy construct s. If exception happens here, 
                                   // s won't be constructed, 
                                   // and the state of the current object (*this) won't be changed
    {
       s.swap (*this);             // Use non-throwing swap to commit the change
       return *this;               // Non-throwing operation
    }