0
0
CppHow-ToBeginner · 4 min read

How to Use std::move in C++: Syntax and Examples

Use std::move in C++ to convert an object into an rvalue reference, enabling efficient transfer of resources instead of copying. It is commonly used to implement move semantics, especially when passing or returning objects to avoid unnecessary copying.
📐

Syntax

The syntax of std::move is simple: it takes an object and returns an rvalue reference to that object.

  • std::move(object): Converts object to an rvalue reference.
  • This does not move anything by itself; it only enables move semantics by allowing move constructors or move assignment operators to be called.
cpp
std::move(object)
💻

Example

This example shows how std::move transfers ownership of a string's data from one variable to another, avoiding a costly copy.

cpp
#include <iostream>
#include <string>
#include <utility> // for std::move

int main() {
    std::string original = "Hello, world!";
    std::string moved_to = std::move(original); // original is now "moved-from"

    std::cout << "Moved to: " << moved_to << std::endl;
    std::cout << "Original after move: '" << original << "'" << std::endl;
    return 0;
}
Output
Moved to: Hello, world! Original after move: ''
⚠️

Common Pitfalls

Common mistakes when using std::move include:

  • Using std::move on objects that should not be moved, leading to undefined or unexpected states.
  • Accessing or using an object after it has been moved from without reinitializing it.
  • Confusing std::move with actually copying or moving data; std::move only casts to an rvalue reference.

Always ensure the moved-from object is not used unless properly reset.

cpp
#include <iostream>
#include <string>
#include <utility>

int main() {
    std::string s1 = "data";
    std::string s2 = std::move(s1); // Correct use

    // Wrong: using s1 after move without resetting
    std::cout << "s1 after move: '" << s1 << "'" << std::endl; // s1 is in valid but unspecified state

    // Right: reset s1 before use
    s1 = "new data";
    std::cout << "s1 after reset: '" << s1 << "'" << std::endl;
    return 0;
}
Output
s1 after move: '' s1 after reset: 'new data'
📊

Quick Reference

Tips for using std::move:

  • Use std::move to enable move semantics and avoid copies.
  • Only use it when you no longer need the original object.
  • After moving, the original object is valid but in an unspecified state.
  • Do not use std::move on const objects because they cannot be moved.

Key Takeaways

Use std::move to convert an object to an rvalue reference for efficient resource transfer.
std::move does not move data itself; it enables move constructors or move assignment operators.
After moving, the original object is valid but may be empty or in an unspecified state.
Avoid using std::move on const objects or when you still need the original object intact.
Always reset or reassign moved-from objects before further use.