What does std::move do in C++?

std::move(x) is only a cast to T&&. The real moving is done by the move constructor or move assignment. After a move, the old object is valid but its value is unspecified (usually empty).

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

int main() {
    std::string a(30, 'x');
    std::string b = a;                      // copy: both have the text
    std::string c = std::move(a);           // move: c takes the buffer
    std::cout << a.size() << ' ' << b.size() << ' ' << c.size() << '\n';
}
Output

0 30 30

Do not use std::move on a returned local variable: return x; already moves, and a manual std::move can stop the compiler from skipping the copy completely (copy elision). See Move Semantics.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.