Skip to content
All library documents

Using Const References for Efficient Read-Only C++ Functions

Article QuantStart

Summary

The document explains how C++ function parameters behave when passed by value, by reference, or by const reference. Passing a large object such as a vector by value creates a copy, which can consume memory and processing time; passing by reference avoids that copy but lets the function change the caller’s object.

For functions that only inspect a large object, the recommended interface is a const reference: it avoids copying while preventing modification through that parameter. A vector norm calculation illustrates why this is clearer and less error-prone than the alternatives. The article suggests using this pattern for read-only mathematical functions, while passing inexpensive built-in types such as integers and doubles by value. It provides conceptual examples rather than benchmarks, and does not discuss newer C++ features or edge cases in const correctness.

Key ideas

  • Passing a large object by value copies its contents and can increase memory use and computation.
  • Passing by reference avoids copying but allows the function to modify the caller’s object.
  • A const reference avoids copying while preventing modification through the function parameter.
  • Simple built-in types are often inexpensive enough to pass by value.

Tags

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.