std::move
std::move is a utility function that converts an object into an Rvalue Reference, enabling move semantics.
It was introduced in C++11 alongside move constructors and move assignment operators.
Purpose
- Allows you to explicitly mark an object as “safe to steal from”
- Signals the compiler that the object can transfer ownership of its resources
- Commonly used when:
- Returning large objects from functions.
- Moving elements into containers.
- Implementing move constructors and move assignment operators.
When to use
Use std::move(x) when:
- You no longer need the original object
xafter the move. - You want to optimize performance by avoiding unnecessary copies.
- The target type supports move semantics.
Avoid using it on:
- Variables you plan to use after
- Temporaries (They’re already rvalues)
constobjects (since they cannot be moved from, only copied).
Source Code (from `)
namespace std
{
template <typename T>
constexpr typename remove_reference<T>::type&& move(T&& t) noexcept
{
using U = typename remove_reference<T>::type;
return static_Cast<U&&>(t);
}
} // namespace stdHow it works
- It does not actually move the object.
- It simply performs a
static_castto an rvalue reference. - That cast allows the compiler to choose a move constructor/assignment when available.
C++ Version
- Introduced in: C++11
- Header:
<utility> - constexpr + noexcept: since C++14 and later