C++: Reasons for passing objects by value
In Java, all variables containing proper objects are actually references (ie 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++ 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).
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
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
}
Instead use
void foo( widget w ) // copy is made here
{
// operate on w itself
}
Doing this also has the benefit of allowing the compiler to move widget
if possible, which is generally more efficient than creating copies.
You're wrong in that you should pass by pointer. If you want to pass by reference, well... simply pass by reference:
void foo(int& x)
{
x = 3;
}
int main()
{
int a = 0;
foo(a);
assert( a == 3 );
}
Also, note that passing by value guarantees that the your variable can't be changed inside the called context. Although so would passing by const
reference...
如果您通过值将对象传递给函数,那么该函数可以自由地将这些对象用作“工作”变量,而不会影响调用者。
链接地址: http://www.djcxy.com/p/20728.html上一篇: 在C ++中通过引用选项传递
下一篇: C ++:按值传递对象的原因