capypad
0 day streak
cpp / intermediate
Snippet

Move Semantics with std::move

Move semantics allow resources (like heap memory) to be moved from one object to another instead of being copied. std::move casts an object to an rvalue, enabling the move constructor to take over the data efficiently.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <vector>
#include <utility>
 
int main() {
std::vector<int> vec1 = {1, 2, 3, 4, 5};
// Transfer ownership of resources from vec1 to vec2
std::vector<int> vec2 = std::move(vec1);
std::cout << "vec2 size: " << vec2.size() << std::endl;
std::cout << "vec1 size: " << vec1.size() << std::endl; // Likely 0
return 0;
}
Breakdown
1
std::vector<int> vec2 = std::move(vec1);
Invokes the move constructor of std::vector, transferring the internal pointer from vec1 to vec2.
2
vec1.size()
After a move, the source object is in a valid but unspecified state, usually empty for containers.