Skip to main content

Section 10.4 When to Use References

So when should you pass by value, reference, or constant reference? Here is a comparison of the three methods and when you should use them.
  • Pass by value: func(type name)
    • Parameter is a copy of passed data.
    • Use when passing a small piece of data (int, double, char). Copying these is no more expensive than making a reference.
    • Use when passing a large piece of data and you want a copy.
  • Pass by reference: func(type& name)
    • Parameter is an alias for the passed variable.
    • Use when passing a large piece of data (string, vector) and you want the function to modify that data.
  • Pass by const reference: func(const type& name)
    • Parameter is an alias for the passed variable but can’t be used to modify it.
    • Passing a large piece of data (string, vector) and you do NOT want the function to modify that data.
Of course, any set of rules will have its exceptions. But the guidelines above describe the preferred method for most situations.
A final point is that a literal value can’t be passed into a function by reference. The reference needs to point at a storage location, not a value. If there is a function void foo(string& s) the following would cause a compiler error:
// error: can't pass a literal by reference
foo("hello world");
The error message would be something like cannot bind non-const lvalue. Storing the string into a variable and passing that variable would work:
string s = "hello world";
foo(s);

Insight 10.4.1.

When in doubt, pass by value. It is the safest option. If you are going to pass by reference, favor using a const reference. Passing off data to another function and letting that function modify the data tends to β€œhide” what is happening and make it harder to reason about what a chunk of code does. A const reference avoids making extra copies but protects us from unwanted side effects that change data unexpectedly.

Checkpoint 10.4.1.

Which would usually be the best way to accept a double parameter we are going to do calculations with?
  • By value
  • By reference
  • A reference opens up the door to unanticipated changes.
  • By const reference
  • Copying a double is not that much work.

Checkpoint 10.4.2.

Which would usually be the best way to accept a vector parameter we are going to do calculations with? (Say find the largest value)
  • By value
  • By value requires copying the entire vector.
  • By reference
  • A reference opens up the door to unanticipated changes.
  • By const reference

Checkpoint 10.4.3.

Which would usually be the best way to accept a vector parameter that we want to be able to modify? (To say remove all of the negative values)
  • By value
  • By value copies the vector. We would only be able to modify the copy.
  • By reference
  • By const reference
  • We can’t modify a const reference.
You have attempted of activities on this page.