0

I read two articles on stackOverflow,one describing the copy and swap idiom and the other talking about move semantics,but I fail to see why we need to swap in the assignment operator when the move constructor or copy constructor has already done that for us

so from what I understand as explained if we use an lvalue the assignment operator will construct an object with the copy constructor if an rvalue it will construct an object with the move constructor,so lets say we choose the latter

lets say we have a function that swaps objects members and below is the assignment operator,so as I said lets say we have an rvalue first the operator= will construct an object with the move constructor so why so we need the swap function here??

we have already accomplished what we want we have made an object with the move constructor and "stolen or taken" the data we needed so whats the need for the extra swap?

aren't we just doing the same thing all over again just swapping?

here are the articles/threads

What are move semantics?

What is the copy-and-swap idiom?

dumb_array& operator=(dumb_array other) // (1)
{
    swap(*this, other); // (2)

    return *this;
}
  • 2
    A copy constructor always creates a new object, an assignment operator never does. So, yes, you need both. –  May 21 '18 at 21:53
  • 1
    You stole the stuff into `other`, and now you want to swap that into `*this` – Passer By May 21 '18 at 21:57

1 Answers1

1

There are two concerns when assigning an object:

  1. We want to get a copy of source's contents into destination.
  2. We want the original contents of destination to be correctly disposed of.

Since we have a copy constructor, the first step is done for us. We could just move the contents of the temporary copy into the destination, but what of concern two?

We have a destructor that handles disposal, so why not use it? If you swap the destination's contents for the temporary's contents, the destruction of the temporary makes sure destination's original are released correctly without having to write new code or duplicate existing code.

Note that Copy and Swap can be heavier-weight than you really need, but it never fails (assuming the functions it relies on are correct), and that makes it a great place to start.

user4581301
  • 29,019
  • 5
  • 26
  • 45