Copy versus Move Semantic

In this lesson, we will compare the performance of the copy and move semantic for the containers in the Standard Template Library (STL).

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:

  1. With copy semantic, a std::bad_alloc will be thrown because the program is out of memory.
  2. The resource of the move operation is afterward in a “valid but unspecified state”.

The second point is demonstrated clearly with std::string.

Get hands-on with 1400+ tech skills courses.