C++ - Move Semantics & R-value References (C++11+)

This is a performance optimization mechanism in C++ that avoids unnecessary copying of heavy objects (like std::vector, std::string, file handles, etc.).


1. Problem Before C++11

Before C++11, when you returned or passed large objects, C++ copied them.

Example:

std::vector<int> createVector() {
    std::vector<int> v = {1,2,3,4};
    return v;   // copy happens (before C++11)
}

Copying large containers is expensive (allocates memory again, duplicates data).


2. What is an R-value?

In simple terms:

  • L-value → Has a name and memory location

    int x = 10;   // x is lvalue
    
  • R-value → Temporary object (no persistent name)

    int y = x + 5;   // (x + 5) is rvalue
    

C++11 introduced r-value references using:

T&&

Example:

int&& r = 10;  // 10 is rvalue

3. Move Semantics Concept

Instead of copying data, C++ can transfer ownership of resources from a temporary object.

Think of it like:

  • Copy → Duplicate the house.

  • Move → Transfer the keys.

After moving, the original object is left in a valid but empty state.


4. Move Constructor

Syntax:

ClassName(ClassName&& other);

Example:

#include <iostream>
#include <vector>

class Test {
    std::vector<int> data;

public:
    Test(std::vector<int> d) : data(d) {}

    // Move constructor
    Test(Test&& other) noexcept {
        data = std::move(other.data);
        std::cout << "Move constructor called\n";
    }
};

std::move() converts an object into an r-value reference so it can be moved instead of copied.


5. Why It Is Important

Move semantics:

  • Improves performance significantly

  • Avoids deep copies of large objects

  • Makes STL containers efficient

  • Enables resource-safe programming

Modern STL containers (like std::vector) heavily use move semantics.


6. Rule of Five

If your class manages resources (like dynamic memory), you should define:

  1. Destructor

  2. Copy constructor

  3. Copy assignment operator

  4. Move constructor

  5. Move assignment operator

This is called the Rule of Five.


7. Real Interview/Practical Use Case

Example:

std::vector<int> v1 = {1,2,3};
std::vector<int> v2 = std::move(v1);

Now:

  • v2 owns the data

  • v1 becomes empty

  • No copy happened


8. When Move Happens Automatically

Move semantics is used when:

  • Returning objects from functions

  • Using std::move()

  • Inserting into STL containers (push_back, emplace_back)

  • Temporary objects are involved


Summary (Direct Points)

  • Introduced in C++11

  • Uses && (r-value reference)

  • Transfers resources instead of copying

  • Requires std::move()

  • Improves performance

  • Part of Rule of Five