I need to swap the value of one structure with another and believe that swap will be faster than copy - am I correct?
#include <iostream>
#include <algorithm>
#include <vector>
class B
{
public:
int y;
std::vector<int> z;
B(){std::cout << "Called" << std::endl;}
private:
int z1;
};
int main()
{
B b1, b2;
b1.z.push_back(1);
std::swap(b1,b2);
std::cout << b2.z[0] << std::endl;
b1.z.push_back(1);
b2 = std::move(b1);
std::cout << b2.z[0] << std::endl;
b1.z.push_back(1);
std::exchange(b1, b2);
std::cout << b2.z[0] << std::endl;
b1.z.push_back(1);
b2 = std::forward<B>(b1);
std::cout << b2.z[0] << std::endl;
}
The above code does the swaps as expected but I am not sure which is the fastest way. My objective is to copy values (swap if it is faster) of one structure variable to another. In the real code the structure will have complex user defined types.
I understand that similarly there will ways to copy - but which way is the best / safe / fast to copy to destination?
Do I need to take care of some operator / constructor to aid it?