复印一体式结构到另一个 [英] Copying one structure to another

查看:106
本文介绍了复印一体式结构到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以通过会员结构成员的复制而不是,我可以对结构做了的memcpy

I know that I can copy the structure member by member, instead of that can I do a memcpy on structures?

时最好什么也别这样?

在我的结构,我有一个字符串也作为成员,我必须复制到具有相同成员的另一个结构。我该怎么做呢?

In my structure, I have a string also as member which I have to copy to another structure having the same member. How do I do that?

推荐答案

由普通分配复制是最好的,因为它更短,更易于阅读,并且具有更高的抽象水平。不要说(到code的人类读者):这些位复制从这里到那里,并要求读者思考的大小参数复制的,你只是在做一个简单的任务(副本从这里这个值来这里)。不可能有任何关于大小是否是正确的犹豫。

Copying by plain assignment is best, since it's shorter, easier to read, and has a higher level of abstraction. Instead of saying (to the human reader of the code) "copy these bits from here to there", and requiring the reader to think about the size argument to the copy, you're just doing a plain assignment ("copy this value from here to here"). There can be no hesitation about whether or not the size is correct.

此外,如果结构在很大程度上填补处理,分配可能使编译器发射的东西更高效的,因为它不具有复制填充(和它知道它是),但 mempcy( )并没有因此它将始终复制字节的确切数字你告诉它复制。

Also, if the structure is heavily padded, assignment might make the compiler emit something more efficient, since it doesn't have to copy the padding (and it knows where it is), but mempcy() doesn't so it will always copy the exact number of bytes you tell it to copy.

如果您的字符串是一个实际的数组,即:

If your string is an actual array, i.e.:

struct {
  char string[32];
  size_t len;
} a, b;

strcpy(a.string, "hello");
a.len = strlen(a.string);

那么你仍然可以使用普通的分配:

Then you can still use plain assignment:

b = a;

要得到一个完整副本。对于可变长度仿照这样的,虽然数据,这是不该做的副本,因为整个阵列将始终被复制的最有效方式。

To get a complete copy. For variable-length data modelled like this though, this is not the most efficient way to do the copy since the entire array will always be copied.

要小心的是,包含指向堆上分配的内存中拷贝结构可有点危险的,因为这样做你的混叠的指针,通常使之暧昧谁拥有指针后复印操作

Beware though, that copying structs that contain pointers to heap-allocated memory can be a bit dangerous, since by doing so you're aliasing the pointer, and typically making it ambiguous who owns the pointer after the copying operation.

对于这些情况深层复制真的是唯一的选择,这点需要在函数中去了。

For these situations a "deep copy" is really the only choice, and that needs to go in a function.

这篇关于复印一体式结构到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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