mardi 26 février 2019

Swap two complex structers - the fastest way to achieve

I need to copy / swap values of one structure to other 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 real time the structure will have complex user defined classes.

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?

Aucun commentaire:

Enregistrer un commentaire