0

I found this great answer from 12 years ago that explains the copy-and-swap idiom and how to implement it in C++11 and C++03.

My question is: is this still the recommended solution or has it changed in later versions of C++? (specifically I'm currently using C++20)

traveh
  • 2,700
  • 3
  • 27
  • 44
  • 2
    _is this still the recommended solution_ is really opinion based ... Does it still work? Yes. – ChrisMM Oct 19 '22 at 20:00
  • 1
    IMHO you should be using RAII types in your class so you don't even need to use the copy and swap idiom. The defaults will just "do the right thing". – NathanOliver Oct 19 '22 at 20:01
  • 1
    Agreed. Copy+Swap really only comes into play when you are writing a class that has to implement the Rule of 3 or Rule of 5 to manage some internal resource properly. If you strive to implement the Rule of 0 instead in your classes, then you don't have to worry about this. – Remy Lebeau Oct 19 '22 at 20:05
  • @NathanOliver: The defaults will NOT do the right thing. The strong exception guarantee does not compose automatically. In particular, the defaulted assignment operator on a composite type will do Copy Subobject A, Swap A, Copy Subobject B, Swap B and the required order is Copy Subobject A, Copy Subobject B, Swap A, Swap B. – Ben Voigt Oct 19 '22 at 20:10
  • Thanks for all the comments... I am however even more confused now as to what would be the best solution... I posted a somewhat more specific question here: https://stackoverflow.com/q/74131192/2375105 – traveh Oct 19 '22 at 20:27
  • The best solution changes depending on the circumstances. If I'm forced to write an assignment operator, I start with Copy and Swap because it's damn near fool-and-bullet-proof. Use and profiling will tell me if I need something different. – user4581301 Oct 19 '22 at 20:50

1 Answers1

1

If you need safety and comfort over performance, it is still best solution. Howard Hinnant recommends you roll your own but only if you really really know how to do it and really really need the last ounce of performance.

Abazoo
  • 57
  • 5