何时传递价值? [英] When to pass by value?

查看:76
本文介绍了何时传递价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的。我想知道是否存在某些情况下您有意在C中按值传递参数的情况。您何时有意将C的传递值用于大型对象?或者,什么时候关心对象参数完全复制到局部变量中?

Dear all. I was wondering if there are examples of situations where you would purposefully pass an argument by value in C. Let me rephrase. When do you purposefully use C's pass-by-value for large objects? Or, when do you care that the object argument is fully copied in a local variable?

EDIT :现在考虑一下,如果您可以避免使用指针,然后这样做。如今,小型应用程序中的几乎所有内容都可以进行深度复制,而浅表复制更容易产生指针错误。

EDIT: Now that I think about it, if you can avoid pointers, then do. Nowadays, "deep" copying is possible for mostly everything in small apps, and shallow copying is more prone to pointer bugs. Maybe.

推荐答案

在C语言中(没有const引用),您按3个原因按值传递。

In C (sans const references), you pass by value for 3 reasons.


  • 您不希望接收函数在其上下文之外修改源。这是在学校教授的标准理由,即为什么要按价值传递。

  • You don't want the source to be modified by the receiving function outside of its context. This is (was) the standard reason taught in school as it why to pass by value.

按价值传递如果价格适合体系结构寄存器中的值,则便宜-如果编译器非常智能,则可能注册。按值传递意味着没有指针创建,也没有对获取的值的引用。这是一个很小的收益,但是在某些情况下确实会累加。

Passing by value is cheaper if the value fits within the architecture's register - or possibly registers if the compiler is very intelligent. Passing by value means no pointer creation and no dereference to get at the value being passed in. A small gain, but it does add up in certain circumstances.

通过值传递只需很少的输入。

Passing by value takes less typing. A weak reason to be sure, but there it is.

const关键字否定了原因1的大部分内容,但是原因2仍然有优点,这也是我按值传递的主要原因。

The const keyword negates most of reason 1, but reason 2 still has merit and is the main reason I pass by value.

这篇关于何时传递价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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