In this really interesting response about the copy-and-swap idiom, it is mentioned that we create a swap()
method in order to avoid code deduplication while creating an assignment operator, when we already have a working copy constructor and a destructor.
Instead of creating a swap()
method just for this purpose, why not just implementing the assignment operator directly with a call to the destructor (this->~MyClass()
, not using the keyword delete
) following by a call to the copy constructor via placement new
?
Considering the exception guarantee :
If the assignment fails with an exception (the copy-and-swap version calls the copy constructor as well), is it still a good idea to continue to use the object in his old state ? I mean at this point the caller do not plan to use the old object anymore because he has a new one.