memcpy和间接引用之间preference [英] Preference between memcpy and dereference

查看:214
本文介绍了memcpy和间接引用之间preference的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当复制在内存中一个已知的结构,你会使用的memcpy或间接引用preFER?为什么?
具体地,在下面的code:

When copying a known struct in memory, would you prefer using memcpy or dereference? why? Specifically, in the following code:

#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;
}

请问你preFER方法1或方法2?我看着由GCC生成的汇编,它似乎是方法2使用较少的指令比起方式1这是否意味着在这种情况下该方法2是preferable?谢谢你。

Would you prefer method 1 or method 2? I looked at the assembly generated by gcc, and it seems that method 2 uses less instructions than method 1. Does it imply that method 2 is preferable in this case? Thank you.

推荐答案

我想不出任何比较好的理由使用的memcpy(),而不是分配复印时,一个结构(只要你不需要做深拷贝或涉及的东西结构黑客或一个的灵活的数组成员的,其中没有在这种情况下适用)。

I can't think of any good reason to use memcpy() rather than an assignment when copying a struct (as long as you don't need to do a deep copy or something involving the struct hack or a flexible array member, none of which apply in this case).

它们具有同样的语义和分配(一)可能给出最优化编译器更多的机会,和(b)具有获取的风险更小的尺寸错误。

They have exactly the same semantics, and the assignment (a) likely gives the compiler more opportunities for optimization, and (b) has less risk of getting the size wrong.

一些的非常的旧C编译器可能不支持结构分配,但是这不再是一个显著的关注。

Some very old C compilers probably didn't support struct assignment, but that's no longer a significant concern.

(还有其他原因在C preFER分配,但是你的问题是关于C)

(There are additional reasons to prefer assignment in C++, but your question is about C.)

顺便提及,在括号

(*pto) = (*pfrom);

是不必要的;一元 * 结合不够紧密,这:

*pto = *pfrom;

是正确和十分明确,大多数读者。

is both correct and sufficiently clear to most readers.

这篇关于memcpy和间接引用之间preference的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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