devnotes.

Move Semantics and Rvalue References

Move semantics (C++11) let a class transfer ownership of its internal resources instead of copying them — a major performance improvement for types that manage heap memory, like std::vector or std::string.

class Buffer {
private:
    int *data;
    size_t size;
public:
    Buffer(size_t n) : data(new int[n]), size(n) {}

    // Move constructor — steals the other object's resource instead of copying it
    Buffer(Buffer&& other) noexcept : data(other.data), size(other.size) {
        other.data = nullptr;   // leave the source in a valid, empty state
        other.size = 0;
    }

    ~Buffer() { delete[] data; }
};

Buffer makeBuffer() {
    Buffer b(1000);
    return b;    // moved out, not copied — no expensive deep copy of 1000 ints
}

Buffer a = makeBuffer();      // move constructor runs
Buffer b = std::move(a);      // explicitly force a move instead of a copy

Buffer&& is an rvalue reference — it binds specifically to temporary values ("rvalues") that are about to be destroyed anyway, like the return value of makeBuffer(). Since that temporary has no further use after the expression, its internal resources can safely be "stolen" (pointer copied, source nulled out) rather than deep-copied, which is exactly what the move constructor above does.

std::move(a) doesn't actually move anything itself — it simply casts a to an rvalue reference, signaling to the compiler "treat this as disposable, feel free to move from it instead of copying." After std::move(a), a is left in a valid-but-unspecified state (its own internals were likely stolen) and shouldn't be used again except to be reassigned or destroyed.

This mechanism is why returning large objects by value from functions is cheap in modern C++ (the compiler moves rather than copies whenever it safely can), and why STL containers holding move-enabled types (like std::vector<std::string>) can grow and reallocate efficiently without deep-copying every element — one of the most impactful changes C++11 introduced.

Move Semantics and Rvalue References in C++ | DevNotes