复制简单结构时memcpy和'='之间的区别 [英] Difference between memcpy and '=' when copying simple struct
问题描述
考虑复制一个简单的结构,不需要特殊的复制语义.
Consider copy a simple struct which doesn't require special copy semantics.
struct A
{
char i
int i;
long l;
double b;
//...maybe more member
}
struct A a;
a.c = 'a'; //skip other member just for illustrate
struct A b;
memset(&a, 0, sizeof(a));
b.c = a.c;
//...for other members, the first way to assign
memcpy(&b, &a, sizeof(b)); //the second way
b = a; //the third way
这3种方法做同样的事情,看来它们都是正确的.我曾经使用'memcpy'复制简单的结构,但现在看来'='可以做同样的事情.那么使用memcpy
和'='有什么区别吗?
The 3 methods do the same thing, and it seems all of them are correct. I used to use 'memcpy' for copying simple structs, but seems now '=' can do the same thing. So is there any difference between using memcpy
and '='?
推荐答案
memcpy
将结构视为字节的连续数组,并仅复制所有字节.结果,它将始终在成员之后复制填充字节.
memcpy
treats the structure as a contiguous array of bytes, and just copies all of them. As a result, it will always copy the padding bytes after members.
=
仅需要复制成员.它可能会或可能不会复制填充.
=
is only required to copy the members. It might or might not copy the padding.
这篇关于复制简单结构时memcpy和'='之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!