在内存中复制已知结构时,您更喜欢使用 memcpy 还是取消引用?为什么?具体来说,在以下代码中:
#include <stdio.h>
#include <string.h>
typedef struct {
int foo;
int bar;
} compound;
void copy_using_memcpy(compound *pto, compound *pfrom)
{
memcpy(pto, pfrom, sizeof(compound));
}
void copy_using_deref(compound *pto, compound *pfrom)
{
*pto = *pfrom;
}
int main(int argc, const char *argv[])
{
compound a = { 1, 2 };
compound b = { 0 };
compound *pa = &a;
compound *pb = &b;
// method 1
copy_using_memcpy(pb, pa);
// method 2
copy_using_deref(pb, pa);
printf("%d %d\n", b.foo, b.bar);
return 0;
}
你喜欢方法一还是方法二?我查看了 gcc 生成的程序集,似乎方法 2 使用的指令比方法 1 少。这是否意味着在这种情况下方法 2 更可取?谢谢你。