Solution: Copy-and-Swap Idiom
Get a detailed explanation of the solution to the copy-and-swap exercise.
We'll cover the following...
Solution
Press + to interact
#include <string>#include <utility>#include <vector>#include<iostream>using namespace std;class Foo {public:Foo(std::string name, std::vector<int> arr, int num ) {s = name;v = arr;num = i;}void swap(Foo& rhs) noexcept {using std::swap;s.swap(rhs.s);v.swap(rhs.v);swap(i, rhs.i);}void print(){cout<<s<<endl;}private:std::string s{};std::vector<int> v{};int i;};int main() {Foo foo("obj1", {1, 2}, 3);Foo foo2("obj2", {4, 5}, 6);foo.print(); // This should print obj1foo.swap(foo2);foo.print(); // After swapping is done this should print obj2}