Java – C: why objects are passed by value

In Java, all variables containing the appropriate object are actually references (i.e. pointers) Therefore, method calls that use these objects as parameters are always "by reference" Calling methods that modify the state of an object also affects the original object (on the caller side)

C is different: parameters here can be passed by value or by reference Calling the mutator method on an object passed by value leaves the original object unaffected I think calling by value creates a local copy of the object

So my first reaction to this - from Java to C - is: when using objects as parameters, always use pointers This gives me the behavior I expect from Java

However, if one does not need to modify the object in the method body, one can also use call by value Does anyone want to do this?

Solution

No, it is always passed by reference in C, unless a function can be called with nullptr as a valid argument If the function does not need to modify parameters, pass the const reference

There are several uses for passing parameters by value

If your function needs to create a copy of an argument, it is best to create this copy by passing values instead of creating a copy within the function For example:

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

But use

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

The benefit of this is to allow the compiler to use the move widget if possible, which is usually more effective than creating a copy

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>