// Illustrates move semantics (with rvalue references) in swap. One without, and one asking for use of move semantics. #include #include using namespace std; template 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 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 void print_vector(const vector& vec){ for(auto e: vec) cout << e << " "; cout << endl << endl; } int main(){ vector 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 }