Using move semantics on containers
suggest changeYou can move a container instead of copying it:
#include <iostream>
#include <utility>
#include <vector>
void print(const std::vector<int>& vec) {
for (int val : vec) {
std::cout << val << ", ";
}
std::cout << std::endl;
}
int main() {
// initialize vec1 with 1, 2, 3, 4 and vec2 as an empty vector
std::vector<int> vec1{1, 2, 3, 4};
std::vector<int> vec2;
// The following line will print 1, 2, 3, 4
print(vec1);
// The following line will print a new line
print(vec2);
// The vector vec2 is assigned with move assignment.
// This will "steal" the value of vec1 without copying it.
vec2 = std::move(vec1);
// vec1 remains valid, but its value is unspecified. It can safely be
// destroyed or assigned a new value; do not assume that it is empty.
// The following line will print 1, 2, 3, 4
print(vec2);
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents