Skip to content

std::move (C++11)

In a Nutshell

Casts an lvalue to an rvalue reference, signaling to the compiler that "this object's resources can be stolen," thereby triggering move construction or move assignment to avoid deep copies.

Header File

<utility>

Core API Cheat Sheet

OperationSignatureDescription
Move cast (Since C++14)remove_reference_t<T>&& move(T&& t) noexcept;Casts object t to an rvalue reference (xvalue)
Perfect forwardingT&& forward(T&& t) noexcept;Preserves value category in forwarding reference scenarios, must be used with T&&
Conditional moveT&& move_if_noexcept(T& t) noexcept;Casts to rvalue if move constructor is non-throwing; otherwise returns lvalue

Minimal Example

Expand (28 lines)Collapse
cpp
#include <utility>
#include <iostream>
#include <vector>

class Buffer {
    std::vector<int> data_;
public:
    Buffer(size_t size) : data_(size) {}
    // Move constructor
    Buffer(Buffer&& other) noexcept : data_(std::move(other.data_)) {
        std::cout << "Move constructor called\n";
    }
    // Move assignment
    Buffer& operator=(Buffer&& other) noexcept {
        if (this != &other) {
            data_ = std::move(other.data_);
        }
        return *this;
    }
};

int main() {
    Buffer a(1000);
    // Explicitly cast lvalue 'a' to rvalue to trigger move
    Buffer b = std::move(a);
    // 'a' is now in a valid but unspecified state
    return 0;
}

Embedded Applicability: High

  • Zero-overhead abstraction: std::move is essentially a static_cast<T&&>, completed at compile time with no runtime cost.
  • Avoid deep copies: Significantly reduces RAM usage and CPU overhead when passing large buffers (like std::vector, std::string).
  • Works with custom resource classes: Can be used to transfer ownership of raw pointers (requires RAII), replacing manual resource handover.
  • Note: The moved-from object is in a "valid but unspecified" state; do not read its value, only assign to it or destroy it.

Compiler Support

GCCClangMSVC
4.63.019.0

See Also


Part of the content references cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05