C++ Move Semantics & Move Constructors: Stealing Resources with Rvalues

Before C++11, returning a large container (like an array or vector) from a function required making an expensive Deep Copy ($O(N)$ time). Move Semantics revolutionized C++ by enabling the transfer of resource ownership from temporary objects in $O(1)$ constant time.

C++ Move Semantics Rvalue Pointer Swap Diagram
Figure 10: Deep Copy (Slow O(N)) vs Move Semantics (Pointer Stealing O(1))

Implementing a Move Constructor

#include <iostream>
#include <utility>

class Buffer {
private:
    int* data;
    int size;

public:
    Buffer(int s) : size(s), data(new int[s]{}) {}

    // Move Constructor (noexcept is best practice for STL vector realloc)
    Buffer(Buffer&& other) noexcept : data(other.data), size(other.size) {
        // STEAL the pointer!
        other.data = nullptr;
        other.size = 0;
        std::cout << "Move Constructor executed: O(1) pointer swap!\n";
    }

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

int main() {
    Buffer b1(1000000); // 1 million integers
    Buffer b2 = std::move(b1); // Blazing fast! Zero integers copied!
    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What does std::move() actually do in C++?

std::move() does NOT move anything at all! It is simply an unconditional static_cast that casts an lvalue expression into an rvalue reference (T&&), signaling to the compiler that the object can be moved from (its resources can be stolen).

Q2. What is the Rule of 5 in modern C++?

If a class customizes any one of the following, it should explicitly define all five: 1. Destructor, 2. Copy Constructor, 3. Copy Assignment Operator, 4. Move Constructor, 5. Move Assignment Operator.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

Constructors & Destructors

Copy constructors and the Rule of Five.

Smart Pointers

How std::unique_ptr relies entirely on move semantics.

C++ std::vector

Move semantics inside std::vector reallocation.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!