Skip to main content

Lesson 3 of 7

rvalue References & Move Semantics

**Rvalue references** (`T&&`) bind to temporaries - they enable **move semantics**. The **move constructor** and **move assignment** operator _steal_ resources from a soon-to-be-destroyed temporary rather than copying them. Moving a `std::vector<int>` is O(1) - just pointer/size swap - vs O(n) for a copy. `std::move` **casts** an lvalue to an rvalue reference - it does NOT move anything itself. The actual move happens in the called move constructor/assignment.

14 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

rvalue References, std::move, Move Constructor & std::forward

rvalue References, std::move, Move Constructor & std::forward
#include <iostream>
#include <string>
#include <vector>
#include <utility>   // std::move, std::forward

class Buffer {
    size_t size_;
    int*   data_;

public:
    explicit Buffer(size_t n)
        : size_(n), data_(new int[n]())
    {
        std::cout << "Buffer(" << size_ << "): allocated
";
    }

    // ── Copy constructor - deep copy (expensive) ──────────────
    Buffer(const Buffer& other)
        : size_(other.size_), data_(new int[other.size_])
    {
        std::copy(other.data_, other.data_ + size_, data_);
        std::cout << "Buffer: COPY (expensive!)
";
    }

    // ── Move constructor - steal resources (O(1)) ─────────────
    Buffer(Buffer&& other) noexcept        // noexcept: required for STL efficiency
        : size_(other.size_), data_(other.data_)
    {
        other.data_ = nullptr;   // leave source in valid but empty state
        other.size_ = 0;
        std::cout << "Buffer: MOVE (cheap!)
";
    }

    // ── Move assignment ────────────────────────────────────────
    Buffer& operator=(Buffer&& other) noexcept {
        if (this != &other) {
            delete[] data_;           // free own resources
            data_      = other.data_;
            size_      = other.size_;
            other.data_= nullptr;
            other.size_= 0;
        }
        return *this;
    }

    ~Buffer() { delete[] data_; }

    size_t size()  const { return size_; }
    bool   empty() const { return size_ == 0; }
};

// ── lvalue vs rvalue - the core distinction ───────────────────
// lvalue: has a name, has address, can be on left of =
// rvalue: temporary, no name, cannot be on left of = (usually)

// T&  binds to lvalues
// T&& binds to rvalues (temporaries) in NON-template context
// T&& in template context = forwarding reference (not rvalue ref!)

void accepts_lvalue(Buffer& b) { std::cout << "lvalue ref: " << b.size() << "
"; }
void accepts_rvalue(Buffer&& b){ std::cout << "rvalue ref: " << b.size() << "
"; }

// ── std::move - cast to rvalue reference ─────────────────────
// std::move(x) does NOT move anything - it casts x to Buffer&&
// The actual move happens when passed to a move constructor

// ── Perfect forwarding in wrapper function ───────────────────
template<typename T>
Buffer wrap_create(T&& arg) {
    // forward: if arg was passed as lvalue, forward as lvalue
    //          if arg was passed as rvalue, forward as rvalue
    return Buffer(std::forward<T>(arg));
}

int main() {
    Buffer b1(10);   // constructed
    Buffer b2 = b1;              // COPY - new allocation
    Buffer b3 = std::move(b1);   // MOVE - b1 is now empty!

    std::cout << "b1.empty()=" << b1.empty() << "
";  // 1 (moved-from)
    std::cout << "b3.size()="  << b3.size()  << "
";  // 10

    // Function overload resolution
    Buffer tmp(5);
    accepts_lvalue(tmp);           // lvalue
    accepts_rvalue(std::move(tmp)); // rvalue (after move, tmp is empty)
    accepts_rvalue(Buffer(7));      // temporary - rvalue

    // ── Return Value Optimisation (RVO/NRVO) ─────────────────
    // When a function returns a local object, the compiler may
    // construct it directly in the caller's memory - zero copies/moves
    // Guaranteed in C++17: prvalue return = no copy, no move
    auto make_buf = [](size_t n) -> Buffer {
        return Buffer(n);   // guaranteed RVO in C++17
    };
    Buffer b4 = make_buf(20);  // typically: no copy, no move

    // ── std::move in containers - the practical pattern ───────
    std::vector<std::string> names;
    std::string name = "Alice";
    names.push_back(name);              // copies "Alice"
    names.push_back(std::move(name));   // moves - name is empty after
    std::cout << "name after move: '" << name << "'
";   // ''
    std::cout << names.size() << "
";  // 2

    // Perfect forwarding
    Buffer b5 = wrap_create(Buffer(15));  // rvalue → move
    Buffer b6 = wrap_create(b3);          // lvalue → copy

    return 0;
}

Common Mistakes

  • Using a moved-from object - after `std::move(x)` and the move constructor/assignment runs, `x` is in a 'valid but unspecified state' (for standard types: empty string, zero-size vector). Don't rely on its value - either reassign or leave it to be destroyed.
  • Not marking move constructor `noexcept` - the STL (especially `std::vector`) checks `noexcept` on move constructors. If your move can throw, `vector` uses the copy constructor instead during reallocations, defeating the purpose of the move constructor.
  • Returning `std::move(local)` from a function - `return std::move(x)` prevents RVO/NRVO. The compiler would have applied copy elision (free), but `std::move` forces a move instead (O(1) but still not as fast). Just `return x;` - the compiler is smarter.

Tip

Tip

Practice rvalue References Move Semantics in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Transferring resource ownership without expensive copies via std::move

Practice Task

Note

Practice Task - (1) Write a working example of rvalue References Move Semantics from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with rvalue References Move Semantics is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • **Rvalue references** (`T&&`) bind to temporaries - they enable **move semantics**.
  • Using a moved-from object - after `std::move(x)` and the move constructor/assignment runs, `x` is in a 'valid but unspecified state' (for standard types: empty string, zero-size vector). Don't rely on its value - either reassign or leave it to be destroyed.
  • Not marking move constructor `noexcept` - the STL (especially `std::vector`) checks `noexcept` on move constructors. If your move can throw, `vector` uses the copy constructor instead during reallocations, defeating the purpose of the move constructor.
  • Returning `std::move(local)` from a function - `return std::move(x)` prevents RVO/NRVO. The compiler would have applied copy elision (free), but `std::move` forces a move instead (O(1) but still not as fast). Just `return x;` - the compiler is smarter.

Topics in This Module

0/7 done