复制简单结构时memcpy和'='之间的区别

A L*_*Lan 2 c c++ struct memcpy

考虑复制一个不需要特殊复制语义的简单结构.

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
Run Code Online (Sandbox Code Playgroud)

3种方法做同样的事情,似乎所有这些方法都是正确的.我曾经使用'memcpy'来复制简单的结构,但现在似乎'='可以做同样的事情.那么使用memcpy和'=' 之间有什么区别吗?

Bar*_*mar 6

memcpy将结构视为一个连续的字节数组,并只复制它们.因此,它将始终复制成员之后的填充字节.

=只需要复制成员.它可能会也可能不会复制填充.