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

Vishwanath Dalvi picture Vishwanath Dalvi · Feb 13, 2011 · Viewed 13.2k times · Source

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

Answer

templatetypedef picture templatetypedef · Feb 13, 2011

There are five 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 as its the only way to get this effect (I treat pass-by-reference and pass-by-pointer interchangeably in this case, though with pass-by-pointer you often have to explicitly check for nullptr.)
  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.
  5. If you're writing a function that might return a very large or uncopyable object, use pass by reference as a way to use a parameter to store the produced value.