Move Semantic

We will talk about some important, often overlooked properties of the move semantic in this lesson.

Containers of the standard template library (STL) can have non-copyable elements. The copy semantic is the fallback for the move semantic. Let’s learn more about the move semantic.

std::move

The function std::move moves its resource.

  • The function needs the header <utility>.
  • The function converts the type of its argument into a rvalue reference.
  • The compiler applies move semantic to the rvalue reference.
  • std::move is under the hood a static_cast to an rvalue reference.
static_cast<std::remove_reference<decltype(arg)>::type&&>(arg);
  • What is happening here?
    • decltype(arg): deduces the type of the argument
    • std::remove_reference<....> removes all references from the type of the argument
    • static_cast<....&&> adds two references to the type

Copy semantic is a fallback for move semantic. This means if we invoke std::move with a non-moveable type, copy-semantic is used. This is due to the fact that an rvalue can be bound to an rvalue reference and a constant lvalue reference.

Get hands-on with 1000+ tech skills courses.