Copy versus Move Semantic
A lot has been written on the advantages of the move semantic over the copy semantic. Rather than an expensive copy operation, we can use a cheap move operation. Let’s break than down further.
There is one subtle difference between copy and move semantic: if we create a new object based on an existing one, the copy semantic will copy the elements of the resource, while the move semantic will move the elements of the resource. Of course, copying is expensive, and moving is cheap, but there are additional serious consequences to this technique:
- With copy semantic, a std::bad_alloc will be thrown because the program is out of memory.
- The resource of the move operation is afterward in a “valid but unspecified state”.
The second point is demonstrated clearly with