Copy vs. Move Semantics

In this lesson, we will compare the performance of the copy and move operations for the containers in the STL.

A lot has been written about the advantages of the move semantic over the copy semantic. Instead of an expensive copy operation, we can use a cheap move operation. But, what does that mean?

The subtle difference is that if we create a new object based on an existing one, the copy semantic will copy the elements of the existing resource, whereas the move semantic will move the elements of the resource. So, of course, copying is expensive and moving is cheap. But there are additional serious consequences.

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

The second point can be explained well by std::string.

Get hands-on with 1200+ tech skills courses.