Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I prefer pass-by-reference or pass-by-value?

Tags:

In what circumstances should I prefer pass-by-reference? Pass-by-value?

like image 827
Vishwanath Dalvi Avatar asked Feb 13 '11 19:02

Vishwanath Dalvi


People also ask

Which is best pass by value or pass by reference?

Passing by reference means the called functions' parameter will be the same as the callers' passed argument (not the value, but the identity - the variable itself). Pass by value means the called functions' parameter will be a copy of the callers' passed argument.

Why pass by reference is better than pass by value?

The main difference between pass by value and pass by reference is that, in a pass by value, the parameter value copies to another variable while, in a pass by reference, the actual parameter passes to the function. A computer program is a set of instructions that directs the CPU to perform a certain task.

Is it always better to pass by reference?

2) For passing large sized arguments: If an argument is large, passing by reference (or pointer) is more efficient because only an address is really passed, not the entire object.

Is it faster to pass by reference or value?

As a rule of thumb, passing by reference or pointer is typically faster than passing by value, if the amount of data passed by value is larger than the size of a pointer.


1 Answers

There are four main cases where you should use pass-by-reference over pass-by-value:

  1. If you are calling a function that needs to modify its arguments, use pass-by-reference or pass-by-pointer. Otherwise, you’ll get a copy of the argument.
  2. If you're calling a function that needs to take a large object as a parameter, pass it by const reference to avoid making an unnecessary copy of that object and taking a large efficiency hit.
  3. If you're writing a copy or move constructor which by definition must take a reference, use pass by reference.
  4. If you're writing a function that wants to operate on a polymorphic class, use pass by reference or pass by pointer to avoid slicing.
like image 55
templatetypedef Avatar answered Oct 20 '22 14:10

templatetypedef