0

I know that using copy and swap to define assignment operators ensures exception security and avoids self-assignment. However, when a large number of move assignments are used, copy and swap will cause performance waste:Why is it not efficient to use a single assignment operator handling both copy and move assignment? When should I use copy and swap and define copy/move assignment operators separately?

After seeing the answer, I still have questions. Does copy-and-swap use efficiency in exchange for convenience, and define the copy/move assignment operator separately to use convenience in exchange for efficiency?

Nater
  • 165
  • 7
  • 1
    the last paragraph of accepted answer already does answer your specific question: Measure. – 463035818_is_not_an_ai Nov 16 '20 at 09:06
  • A general question like this, while interesting, will attract opinion based answers. If you have some specific concerns about performance that you noticed while profiling, you need to add those details to the question. – cigien Nov 16 '20 at 13:12
  • But I think these two ways of defining assignment operators are to choose between performance and convenience – Nater Nov 16 '20 at 14:51

1 Answers1

6

copy and swap will cause performance waste

[citation needed]

You don't guess performance issues: you bench them, you measure them. After you've done that and you know you have a performance issue you can ask yourself how to improve things.

When should I use copy and swap and define copy / move assignment operators separately?

This should be your default choice. If one day you do have performance issues, profile your code and see from there.

YSC
  • 38,212
  • 9
  • 96
  • 149
  • This approach might be generally true, but not in all cases. What if you are writing a library? You might hardly bench all possible uses of it. Then, some intuition may be useful. For example, copy-and-swap for `std::vector` would be inefficient, if the capacity of the copied-to vector was higher or equal to the size of the copied-from vector. – Daniel Langr Nov 16 '20 at 09:24
  • @DanielLangr I expect from someone writing a general-purpose library to have the insight to come up with actual problematic cases, and benchmark those. Compilers are getting better by the day, and every day I see experienced developers trying to outsmart them with complicated designs. When those complicated designs are benchmarked against more simple ones, it is not rare to see the simple one winning. – YSC Nov 16 '20 at 09:42
  • Copy and swap trade efficiency for convenience, and defining copy / move assignment operators is to trade convenience for efficiency. Is that the statement? – Nater Nov 16 '20 at 10:02