Copy-swap idiom not recommended?

162 Views Asked by At

For a long time time I though that the correct way to implement a copy assignment (for a non trivial class) was to use the copy-swap idiom.

struct A{
   ... pointer to data
   A(A const& other){
       ... complicated stuff, allocation, loops, etc
   }
   void swap(A& other){... cheap stuff ...}
   A& operator=(A const& other){
      A tmp{other};
      swap(other);
      return *this;
   }
};

But then I heard this talk https://www.youtube.com/watch?v=vLinb2fgkHk by Howard Hinnant where he says that the copy-swap idiom is good to fulfill the strong-exception guarrantee but it is an overkill in general.

He mentions that here: https://youtu.be/vLinb2fgkHk?t=2616

So he suggests implement the copy assignment explicitly and have a separate function strong_assing(A& target, A const& source) containing the copy-swap.

What I don't understand is how A& operator=(A const& other) should be implemented then?

Does he suggest to have something like this?

   A& operator=(A const& other){
        ... don't allocate if not necessary
        ... loop element by element
        ... clean the bare minimum if there is a throw 
   }

Is this what std::vector implementations do then? That is, they do not use the copy-swap idiom at the end? Doesn't the standard vector requires the strong-exception guarantee?

0

There are 0 best solutions below