ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

C++ Tutorial• 7 min read

Move Semantics & Rvalue References (&&)

std::move, avoiding deep copies of heap resources, and move constructors

Introduced in C++11, Move Semantics eliminate unnecessary deep copies of temporary objects by transferring resource ownership (pointers) directly via Rvalue References (&&).

Lvalues vs Rvalues and std::move

Lvalue: An object with an identifiable memory address that persists beyond a single expression (e.g. named variables).

Rvalue: A temporary value that does not persist (e.g. return values from functions, string literals).

std::move(lval): Casts an lvalue to an rvalue reference, allowing its internal heap buffers to be "stolen" by move constructors rather than copied.

Move Semantics in Practice
#include <iostream>
#include <vector>
#include <string>

int main() {
    std::string heavyData = "Multi-megabyte dataset string...";

    // std::move transfers pointer ownership without copying memory!
    std::string destination = std::move(heavyData);

    std::cout << "Destination: " << destination.substr(0, 14) << "..." << std::endl;
    // heavyData is now in a valid but empty moved-from state!
    std::cout << "Original size: " << heavyData.size() << std::endl; // 0
    return 0;
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What does `std::move()` actually do in Modern C++?