| references/swap1.cc - Two versions of swap - with Lvalue references and Rvalue references. | Lecture 2 - slide 22 : 29 Program 1 |
// Illustrates move semantics (with rvalue references) in swap. One without, and one asking for use of move semantics.
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
void swap(T& a, T& b){
T temp {a}; // COPIES a to temp
a = b; // COPIES b to b
b = temp; // COPIES temp to b
}
template<typename T>
void swap1(T& a, T& b){ // move forces a Rvalue reference
T temp {move(a)}; // MOVES a to temp
a = move(b); // MOVES b to a
b = move(temp); // MOVES temp to b
}
template<typename T>
void print_vector(const vector<T>& vec){
for(auto e: vec) cout << e << " ";
cout << endl << endl;
}
int main(){
vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9}, // Two 'large' vectors
w{5, 2, 0};
print_vector(v); // 1 2 3 4 5 6 7 8 9
print_vector(w); // 5 2 0
swap(v, w); // Uses swap by copying
print_vector(v); // 5 2 0
print_vector(w); // 1 2 3 4 5 6 7 8 9
print_vector(v); // 5 2 0
print_vector(w); // 1 2 3 4 5 6 7 8 9
swap1(v, w); // Uses swap by moving
print_vector(v); // 1 2 3 4 5 6 7 8 9
print_vector(w); // 5 2 0
}