Move Semantics, Rvalues & std::move Cast

🔴 Advanced

📖 Definition & Technical Accuracy

Introduced in C++11, Move Semantics transfers internal heap resources from temporary or expiring objects (rvalues/xvalues) to new owners instead of performing expensive deep copies.

  • Rvalue Reference (T&&): Binds to temporary prvalues and expiring xvalues.
  • std::move(x): A pure static cast (static_cast<T&&>(x)) that converts an lvalue into an rvalue reference. std::move itself does NOT move any memory or resources; it simply enables the move constructor or move assignment operator to be selected during overload resolution.

💡 Complete Code Example

#include <iostream>
#include <utility>
#include <vector>

class Buffer {
public:
    std::vector<int> data;

    Buffer(size_t size) : data(size, 42) {
        std::cout << "Buffer Constructed (" << size << " elements)\n";
    }

    // Move Constructor
    Buffer(Buffer&& other) noexcept : data(std::move(other.data)) {
        std::cout << "Buffer MOVED (Zero Allocation Copy!)\n";
    }
};

int main() {
    Buffer b1(1000000);
    Buffer b2 = std::move(b1); // std::move casts b1 to rvalue, triggering move constructor
    return 0;
}