Does C++ pass objects by value or reference?

2019-01-13 10:36发布

问题:

A simple question for which I couldn't find the answer here.

What I understand is that while passing an argument to a function during call, e.g.

void myFunction(type myVariable)
{
}

void main()
{
    myFunction(myVariable);
}

For simple datatypes like int, float, etc. the function is called by value.

But if myVariable is an array, only the starting address is passed (even though our function is a call by value function).

If myVariable is an object, also only the address of the object is passed rather than creating a copy and passing it.

So back to the question. Does C++ pass a object by reference or value?

回答1:

Arguments are passed by value, unless the function signature specifies otherwise:

  • in void foo(type arg), arg is passed by value regardless of whether type is a simple type, a pointer type or a class type,
  • in void foo(type& arg), arg is passed by reference.

In case of arrays, the value that is passed is a pointer to the first elements of the array. If you know the size of the array at compile time, you can pass an array by reference as well: void foo(type (&arg)[10]).



回答2:

C++ always gives you the choice: All types T (except arrays, see below) can be passed by value by making the parameter type T, and passed by reference by making the parameter type T &, reference-to-T.

When the parameter type is not explicitly annotated to be a reference (type &myVariable), it is always passed by value regardless of the specific type. For user-defined types too (that's what the copy constructor is for). Also for pointers, even though copying a pointer does not copy what's pointed at.

Arrays are a bit more complicated. Arrays cannot be passed by value, parameter types like int arr[] are really just different syntax for int *arr. It's not the act of passing to a function which produces a pointer from an array, virtually every possible operation (excluding only a few ones like sizeof) does that. One can pass a reference-to-an-array, but this explicitly annotated as reference: int (&myArray)[100] (note the ampersand).



回答3:

C++ makes both pass by value and pass by reference paradigms possible.

You can find two example usages below.

http://www.learncpp.com/cpp-tutorial/72-passing-arguments-by-value/

http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/

Arrays are special constructs, when you passed an array as parameter, a pointer to the address of the first element is passed as value with the type of element in the array.

When you passed a pointer as parameter you implement the pass by reference paradigm yourself , as in C. Because when you modify the object in the specified address, you exactly modify the object in the caller function.



回答4:

C++ passes arguments that are no pointers (int*) or references (int&) by value. You cannot modify the var of the calling block in the called function. Arrays are pointers.