结构的一部分的记忆 [英] memcpy of a part of a struct

查看:124
本文介绍了结构的一部分的记忆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个struct/class,它是部分的Plain Old Data(POD).

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;
};

我经常复制S类的对象. 我想用memcpy复制它,但是S :: more阻止了它. 我想避免调用4个memcpy,而只用一个就可以提高性能. 我应该这样做吗?

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);

我不能将它们打包在单独的结构中,因为它会破坏所有使用pod1-pod4的代码.

I can't pack them in separate struct since it would clobber all the code that uses pod1 - pod4.

什么是最佳解决方案?

推荐答案

最好的解决方案是依靠C ++自动复制构造函数和复制运算符.这样,编译器就有机会了解您的代码并对其进行优化.尝试避免在C ++代码中使用memcpy.

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:

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

这篇关于结构的一部分的记忆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆