memcpy和间接引用之间preference

编程入门 行业动态 更新时间:2024-10-25 05:12:39
本文介绍了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

本文发布于:2023-11-04 01:09:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556544.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:memcpy   preference

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!