I have a struct/class which is partiall Plain Old Data (POD).
struct S {
// plain-old-data structs with only arrays and members of basic types (no pointers);
Pod1 pod1;
Pod2 pod2;
Pod3 pod3;
Pod4 pod4;
vector<int> more;
};
I copy objects of class S a lot.
I would like to copy it with memcpy, but S::more prevents it.
I would like to avoid call to 4 memcpy’s and make it all with one for an extra bit of performance.
Should I do someting like this?
memcpy(s1, s2, sizeof(Pod1) + sizeof(Pod2) + sizeof(Pod3) + sizeof(Pod4);
I can’t pack them in separate struct since it would clobber all the code that uses pod1 – pod4.
What is the best solution?
The best solution is to rely on C++ automatic copy constructor and copy operator. The compiler has then a chance to understand your code and optimize it well. Try to avoid memcpy in C++ code.
If you need to copy only part of the structure, create a method for it: