C ++:按值传递对象的原因 [英] C++: Reasons for passing objects by value

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

问题描述

在Java中,所有包含适当对象的变量实际上都是引用(即指针).因此,以这些对象作为参数的方法调用始终是按引用".调用修改对象状态的方法也会影响原始对象(在调用方).

In Java, all variables containing proper objects are actually references (i.e. pointers). Therefore, method calls with these objects as arguments are always "by reference". Calling a method which modifies the state of the object also affects the original object (on the caller side).

C ++有所不同:这里的参数可以按值传递或按引用传递.在通过值传递的对象上调用mutator方法会使原始对象不受影响. (我想按值调用会创建对象的本地副本.)

C++ is different: Here arguments can be passed by value or passed by reference. Calling a mutator method on an object which was passed by value leaves the original object unaffected. (I suppose call by value creates a local copy of the object).

所以我对此的第一反应-从Java到C ++-是:在将对象用作参数时,总是使用指针.这给了我Java所期望的行为.

So my first response to this - coming from Java to C++ - is: ALWAYS use pointers when using objects as arguments. This gives me the behavior I have come to expect from Java.

但是,在不需要修改方法主体中的对象的情况下,也可以使用按值调用".有什么理由要这样做吗?

However, one could also use "call by value" in case one does not need to modify the object in the method body. Are there reasons why one would want to do this?

推荐答案

在将对象用作参数时总是使用指针

ALWAYS use pointers when using objects as arguments

否,在C ++中,始终通过 reference 传递,除非可以使用nullptr作为有效参数来调用您的函数.如果函数不需要修改参数,则通过const引用传递.

No, in C++ always pass by reference, unless your function can be called with nullptr as a valid argument. If the function does not need to modify the argument, pass by const reference.

按值传递参数有多种用途.

Passing arguments by value has several uses.

如果函数需要创建参数的副本,则最好通过按值传递而不是在函数内创建副本来创建此副本.例如:

If your function needs to create a copy of the argument it is better to create this copy by passing by value rather than creating a copy within the function. For instance:

void foo( widget const& w )
{
  widget temp( w );
  // do something with temp
}

代替使用

void foo( widget w )  // copy is made here
{
  // operate on w itself
}

这样做还有一个好处,就是允许编译器 移动 widget(如果可能),通常比创建副本更有效.

Doing this also has the benefit of allowing the compiler to move widget if possible, which is generally more efficient than creating copies.

这篇关于C ++:按值传递对象的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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