将一种结构复制到另一种结构 [英] Copying one structure to another

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

问题描述

我知道我可以逐个成员复制结构成员,而不是我可以对结构执行 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?

推荐答案

通过简单的赋值复制是最好的,因为它更短、更容易阅读并且具有更高的抽象级别.而不是说(对代码的人类读者)从这里复制这些位到那里",并要求读者考虑复制的大小参数,你只是在做一个简单的赋值(从从这里到这里").对于尺寸是否正确,可以毫不犹豫.

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天全站免登陆