Junior — Middle
How is ownership transfer of objects implemented using std::move in C++?
sobes.tech AI
Answer from AI
In C++, the std::move function does not transfer ownership by itself, but merely converts an object into an rvalue reference, which allows the use of move semantics.
When you call std::move(obj), you are telling the compiler that the object obj can be "moved" (i.e., its resources can be transferred to another object without copying).
Example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2 = std::move(v1); // resources of v1 are moved to v2
std::cout << "v1 size: " << v1.size() << "\n"; // usually 0
std::cout << "v2 size: " << v2.size() << "\n"; // 3
}
Here, std::move allows calling the move constructor or move assignment operator, which implement the transfer of resources (for example, data pointers) from v1 to v2. After the move, v1 remains in a valid but unspecified state.
Thus, std::move is a tool for explicitly indicating that an object can be moved, not copied.