我有一个struct/class,它是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;
};
Run Code Online (Sandbox Code Playgroud)
我很多时候复制了S类的对象.我想用memcpy复制它,但S :: more阻止了它.我想避免调用4个memcpy,并将其全部用于一个额外的性能.我应该这样做吗?
memcpy(s1, s2, sizeof(Pod1) + sizeof(Pod2) + sizeof(Pod3) + sizeof(Pod4);
Run Code Online (Sandbox Code Playgroud)
我不能将它们打包在单独的结构中,因为它会破坏使用pod1-pod4的所有代码.
什么是最好的解决方案?
Kar*_*nek 10
最好的解决方案是依靠C++自动复制构造函数和复制运算符.然后,编译器有机会理解您的代码并对其进行优化.尽量避免在C++代码中使用memcpy.
如果只需要复制部分结构,请为其创建一个方法:
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;
};
void copyPartOfS(S& to, const S& from)
{
s.pod1 = from.pod1;
s.pod2 = from.pod2;
s.pod3 = from.pod3;
s.pod4 = from.pod4;
}
...
S one, two;
one = two; // Full copy
copyPartOfS(one, two); // Partial copy
Run Code Online (Sandbox Code Playgroud)