Copy-swap idiom not recommended?

陌路散爱 提交于 2019-12-22 00:23:37

问题


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?

来源:https://stackoverflow.com/questions/51463356/copy-swap-idiom-not-recommended

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!