-2

I saw this: question

But the answers there are very complicated for a C++ newbie like me. I would like it if someone could help me out.

CLASSA & operator=(CLASSA && other); //move assignment operator

CLASSA & operator=(CLASSA  other); //copy assignment operator

I am still failing to see why we require both of these? They basically do the same thing? So what is the difference and where would you use one over the other?

  • Not the answer, but copy assignment should take `const CLASSA &other` as a parameter instead. – HolyBlackCat Jun 18 '17 at 21:13
  • 1
    When implementing the move assignment operator you can take advantage of the fact the the `other` variable is known to be a temporary and is about to be destroyed (on return from the call). So if you want to you can take advantage of this and "steal" it's contents instead of copying them. So long as you leave `other` in a valid state (so it can be destroyed cleanly) no code will be aware of what you did. – Richard Critten Jun 18 '17 at 21:18
  • 1
    You need both only when they *don't* do the same thing. – Bo Persson Jun 18 '17 at 21:24

1 Answers1

1

First of all, copy assignment operator usually uses "const CLASSA &" as parameter instead of simply "CLASSA".

Usually, there are 2 uses cases of move:

  1. Optimization: where copy is expensive, but move is cheap. For example, with a typical implementation of std::string, it can be moved cheaply. Copy is more expensive (memory allocation + copy). Move can be used, for example, when a std::vector<std::string> needs to grow. In the old days (when no rval ref existed), std::vector<std::string> grow was implemented like this: allocate a new bigger area, then copy (slow) strings into the new place, then destroy strings at the old place. Now, with rval refs available, this happens: allocate a new bigger area, then move (fast) strings into the new place.
  2. Where copy is forbidden by design, but a move is possible. For example, std::unique_ptr
geza
  • 28,403
  • 6
  • 61
  • 135