Search⌘ K

Move Semantic

Explore how move semantic in Modern C++ enhances resource management by prioritizing efficient resource transfer over copying. Understand the role of std::move, move constructors, and move assignment operators in STL containers and user-defined classes. Learn the rules governing automatically generated special methods to write optimized, maintainable embedded code.

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

...