Search⌘ K

Copy vs. Move Semantics

Explore the fundamentals of copy versus move semantics in C++. Understand how move semantics improve efficiency by transferring resources instead of copying them. This lesson covers the implications for memory management, the use of std::move, and practical examples such as swapping objects using move operations.

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. ...