0

Recently, I have stumbled over this pattern:

class Foo {
   Foo() = default;
   Foo(const Foo &) = default;
   Foo(Foo &&) = default;
   Foo & operator=(Foo rhs) {
      swap(rhs);
      return *this;
   }
};

A close look at this pattern revealed that, thanks to copy elision, this single assignment function gives for free both move assignment and the copy assignment by "copy and swap". Since it is so handy, why isn't it a "mainstream pattern". Is there any by doing it this way?

Note: a custom made copy constructor without temporaries could yield the operation in fewer steps but, For this question, what benefit explicitly writing copy and move assignment around swap could bring.

In respect to possible duplicate of question "what is the copy-and-swap idiom", my question assumes the reader already knows what it is.

Thanks

user666412
  • 528
  • 8
  • 18
  • 2
    Wasted resources doing what could easily be implemented, especially for a move. Moves don't need to copy first, they usually steal the resources, so why copy everything when you can just take it, which is typically much faster? – ChrisMM Oct 25 '19 at 09:50
  • Possible duplicate of [What is the copy-and-swap idiom?](https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom) – L. F. Oct 25 '19 at 10:21
  • @ChrisMM Pass by value doesn't mean copying. Moving is also a possibility. – L. F. Oct 25 '19 at 10:21
  • _"why isn't it a 'mainstream pattern'"_ What makes you think it isn't? Are you just asking why more people don't write better code? ;) – Lightness Races in Orbit Oct 25 '19 at 10:38
  • Copy elision is guaranteed since C++17 only. Try adding some members to Foo, like std::vector, and compile with MSVC. – rustyx Oct 25 '19 at 10:41
  • @Lightness Races in Orbit haven't seen much references to it in literature or in the web ... – user666412 Oct 25 '19 at 10:46
  • @user666412 Your book surely discusses it. – Lightness Races in Orbit Oct 25 '19 at 10:55

0 Answers0