In C++, when should a read-only parameter be passed by value rather than by const reference?
answer
- cost of copying versus indirection
- small trivially copyable types
- registers versus memory loads
- const& can alias
basics
~20 sPass small, cheap-to-copy types such as int, double or a two-double Point by value; pass types whose copy is expensive, such as std::string or std::vector, by const reference. By-value parameters also cannot alias the caller's other arguments.
solid answer
~40 sA `const&` parameter passes an address, so the callee pays an indirection on every read and the compiler must assume the referent can change through any other pointer or reference it can't see. For a 16-byte `Point{double x, y}`, passing by value is usually cheaper: on the common 64-bit ABIs such a struct travels in registers - Clang on arm64 passes it in `d0`-`d3` with no loads - and the callee owns a private copy. For `std::string` or `std::vector`, copying may allocate and copy every element, so `const std::string&` (or `std::string_view`) wins for read-only use. Register passing is an ABI choice, not a standard rule. The aliasing hazard is real either way: with `const Point& delta`, `offset(points, points[0])` changes `delta` mid-loop.
code
cpp · 20 lines#include <cstdio>
#include <vector>
struct Point { double x, y; };
// delta by const&: it may alias an element being modified.
void offset_ref(std::vector<Point>& pts, const Point& delta) {
for (Point& p : pts) { p.x += delta.x; p.y += delta.y; }
}
// delta by value: a private copy, immune to aliasing and cheap for 16 bytes.
void offset_val(std::vector<Point>& pts, Point delta) {
for (Point& p : pts) { p.x += delta.x; p.y += delta.y; }
}
int main() {
std::vector<Point> a{{1, 1}, {10, 10}}, b = a;
offset_ref(a, a[0]); // after a[0] doubles, delta reads (2, 2)
offset_val(b, b[0]); // delta stays (1, 1)
std::printf("ref: %.0f val: %.0f\n", a[1].x, b[1].x);
}go deeper
Recall the rule of thumb: cheap types such as int, double and small structs by value, and expensive owning types such as std::string or std::vector by const reference.
Explain the trade-off as copy cost against indirection, show the aliasing bug a const& parameter allows, and note that register passing is the ABI's choice.
Read the generated code for a hot function, recognize when aliasing forces reloads, and recognize sink parameters where by value plus a move beats const&.
Turn the rule of thumb into a written convention with a size threshold and named exceptions, so reviews stop re-arguing each signature.
## What each form costs A parameter passed **by value** is a new object initialized from the argument: for a class type that runs the copy (or move) constructor. A parameter passed **by `const&`** is an alias for the caller's object: nothing is copied, but every use reads through an address. | Parameter type | Cost at the call | Cost in the body | Aliasing | |---|---|---|---| | `Point p` (16 bytes, trivially copyable) | copy 16 bytes, usually into registers | none | private copy | | `const Point& p` | pass an address | a load for each member read | may alias other arguments or globals | | `std::string s` | copy constructor, may allocate | none | private copy | | `const std::string& s` | pass an address | indirection | may alias | So the decision is "is the copy cheaper than the indirection plus lost optimization?". For **fundamental types and small trivially copyable structs**, yes. For types that own heap memory, no. ## Registers: an implementation fact, not a standard rule The standard says nothing about registers; the calling convention (the platform **ABI**) does. On the mainstream 64-bit ABIs a small aggregate of floating-point members travels in floating-point registers. Compiled with Apple clang at `-O2` for arm64, a by-value `dot(Point, Point)` multiplies straight out of `d0`-`d3`, while the `const Point&` version first loads both points from memory with `ldp`. The same pattern appears on x86-64 Linux, where the by-value version reads `xmm0`-`xmm3` and the reference version reads memory through `rdi` and `rsi`. Each ABI has its own size limits and classification rules - so "pass by value up to two or three machine words" is a guideline grounded in common ABIs, not a guarantee. Triviality matters as much as size. On the Itanium-based C++ ABIs that Clang and GCC use, a class with a non-trivial copy or move constructor or destructor is passed through a hidden pointer to a caller-made copy, however small it is: with Apple clang on arm64, a by-value `struct Handle { int fd; ~Handle(); }` is read with `ldr w0, [x0]`, while the same struct without the destructor simply arrives in `w0`. So a small RAII handle taken by value still costs a memory round trip - the reason to pass it by value is ownership, not speed. ## Aliasing: the bug, not just the optimization A `const&` promises only that the callee won't modify the object **through that reference**. Someone else may: ```cpp void offset_ref(std::vector<Point>& pts, const Point& delta); offset_ref(pts, pts[0]); // delta IS pts[0]; after the first iteration it has doubled ``` With `{1,1}` and `{10,10}`, the by-reference version moves the second point to 12, the by-value version to 11. Beyond correctness, the possibility of aliasing forces the compiler to reload `delta.x` after every store into `pts`, because the store might have changed it. A by-value parameter removes both problems for small types. ## std::string and other owning types `std::string` copies its characters, and when the string does not fit the implementation's small-string buffer, a copy allocates. For a read-only parameter: - `const std::string&` avoids the copy when the caller has a `std::string`, but builds a temporary when the caller passes a literal; - `std::string_view` (C++17) avoids both, at the cost of not guaranteeing a null terminator - the trade-offs belong to the lesson on string views; - passing `std::string` by value is right only when the function **keeps** a copy anyway, a "sink" parameter that it then moves into a member; the move mechanics are covered with move semantics. ## A rule of thumb you can defend 1. Fundamental types, enums, pointers, iterators, `std::string_view`, `std::span` and small trivially copyable structs: **by value**. 2. Types whose copy allocates or is large (`std::string`, `std::vector`, `std::map`, big structs): **by `const&`** for read-only use. 3. Polymorphic objects: always by reference or pointer, since by value would slice to the static type. 4. Templates where the type is unknown: `const T&` is the safe default unless you know `T` is cheap. 5. When in doubt on a hot path, read the generated code or measure; the ABI decides. ## What interviewers listen for - the trade-off stated as copy cost versus indirection and aliasing, not "references are always faster"; - the ABI caveat: register passing is an implementation property; - the aliasing bug with `const&` and why by-value parameters are immune; - knowing that `const&` to a different type still pays for a conversion.
- Is a by-value parameter always copied, even when the caller passes a temporary?No. Since C++17, a prvalue argument such as `make_point()` or `Point{1, 2}` initializes the parameter directly - guaranteed copy elision - so no copy or move happens. A by-value parameter only copies when the caller passes an lvalue it keeps using. Guaranteed elision itself is covered with copy elision.
- Why should a polymorphic Shape never be a by-value parameter?A by-value `Shape` parameter is a new `Shape` object copy-constructed from the argument's `Shape` base subobject, so a `Circle` argument is sliced: its derived members and its dynamic type are lost, and virtual calls dispatch to `Shape`'s versions. Polymorphic types are passed by `const Shape&`, `Shape&` or pointer.
- const& is always faster than passing by value
- Passing a Point by value always forces a copy through memory
- A const& parameter cannot change while the function runs
- The C++ standard requires small structs to be passed in registers
- Passing std::vector by value is free because it only copies a pointer