0

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.

Community
  • 1
  • 1
infiniteLoop
  • 383
  • 2
  • 12
  • 1
    You missed quoting this bit _" and providing a strong exception guarantee."_ – Richard Critten Feb 01 '17 at 22:00
  • 3
    Think what happens if the constructor throws an exception – M.M Feb 01 '17 at 22:02
  • I understand but if the assignment fails with an exception, 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 – infiniteLoop Feb 01 '17 at 22:13
  • The point is to ensure that if an exception is thrown in the assignment, the assigned-to object remains in the state it was before the assignment was attempted. – juanchopanza Feb 01 '17 at 22:22
  • @juanchopanza please see my comment – infiniteLoop Feb 01 '17 at 22:23
  • 1
    @mikeDundee The point is in that in some situations you want assignments to have roll-back semantics under exceptions. Copy and swap is a way to guarantee that. If you don't need it, then there is little point in using it, because it can have a performance impact for no gain. – juanchopanza Feb 01 '17 at 22:26
  • @juanchopanza : I see the assignment can be just a part of a set of instructions that you may want to rollback – infiniteLoop Feb 01 '17 at 22:35

0 Answers0