The Analogy: Editing the Original Document
Pass by value is emailing someone a copy of a document. They can scribble all over it and your file is untouched — safe, but if the document is 400 pages, making the copy costs something.
Pass by reference is sharing a link to the live document. There is one file. Their edits are your edits. That is exactly what you want when the point is to change something, and exactly what you must guard against when it is not — which is what const is for. A const reference is a read-only link: instant to share, impossible to edit through.
Syntax or Core Structure
The ampersand goes on the parameter type in the function's own declaration. Call sites look identical either way.
#include <iostream>
#include <string>
#include <vector>
void byValue(int n) { n = 99; } // edits a copy
void byRef(int& n) { n = 99; } // edits the caller's variable
void readOnly(const std::string& s) { // no copy, cannot modify
std::cout << s.size() << "\n";
}
// The classic: swap is impossible without references (or pointers)
void swapInts(int& a, int& b) {
const int temp = a;
a = b;
b = temp;
}
// Modify every element of a container in place
void doubleAll(std::vector<int>& data) {
for (int& x : data) { x *= 2; }
}
int main() {
int a = 1;
byValue(a);
std::cout << a << "\n"; // 1 -- unchanged
byRef(a);
std::cout << a << "\n"; // 99 -- changed
int x = 10, y = 20;
swapInts(x, y);
std::cout << x << " " << y << "\n"; // 20 10
std::vector<int> nums{1, 2, 3};
doubleAll(nums);
std::cout << nums[2] << "\n"; // 6
return 0;
}
Nothing at the call site marks byRef(a) as modifying a. That is the one real cost of references over pointers: you must read the signature to know. It is why non-const reference parameters should be rare and obviously named.
Technical Depth: The Cost and the Contract
What a copy actually costs
For an int or a double, a copy is one machine instruction — passing by reference can even be slower, because the function must dereference to reach the value. For anything owning heap memory, the copy allocates.
struct Order {
std::string customer; // heap allocation
std::vector<std::string> lines; // heap allocation + one per string
double total;
};
void byValue(Order o); // copies the string and every line
void byConstRef(const Order& o); // copies nothing
Call byValue in a loop over 10,000 orders and you have made 10,000 pointless allocations. The rule of thumb: pass by value up to roughly two machine words (int, double, std::string_view, a small Point), and by const reference above that.
const is a contract, not just a safety net
const on a reference parameter does three things at once. It stops you modifying the argument by accident. It documents intent in the signature, so a caller need not read the body. And it widens what the function accepts:
void takesRef(std::string& s);
void takesConstRef(const std::string& s);
std::string name = "Ada";
takesRef(name); // OK
takesConstRef(name); // OK
takesRef("literal"); // ERROR: cannot bind a temporary to std::string&
takesConstRef("literal"); // OK: const& happily binds a temporary
takesConstRef(name + " L."); // OK: binds the temporary result
A missing const therefore breaks call sites that never wanted to modify anything.
Choosing a parameter style
| Style | Copies? | Caller's value can change? | Use when |
|---|---|---|---|
T | Yes | No | Small, cheap types |
const T& | No | No | Large read-only inputs — the default |
T& | No | Yes | The function's job is to modify it |
T* | No | Yes | The argument is genuinely optional (nullptr) |
const T* | No | No | Optional read-only input |
std::string_view | No | No | Read-only text from any source |
References cannot be null, and cannot be reseated
int a = 1, b = 2;
int& r = a; // must be initialised
r = b; // assigns 2 INTO a -- does not rebind r
std::cout << a; // 2
There is no such thing as a null reference, so a function taking T& never needs a null check. That is a real advantage over pointers. The flip side: if the argument might legitimately be absent, a reference cannot express that — use T* and check it.
Dangling: the hazard that survives testing
A reference is only as good as the object behind it. Three ways to break one:
std::vector<int> v{1, 2, 3};
int& first = v[0];
v.push_back(4); // may reallocate -- 'first' now dangles
first = 10; // undefined behaviour
const std::string& bad = getTemporary(); // lifetime extended... only for a temporary
// bound directly, not one returned by ref
Any operation that can reallocate a container (push_back, insert, resize, reserve) invalidates references to its elements. Take the reference after you finish growing, or store an index instead.
Modifying while iterating
The range-based for needs & in two places to actually change a container:
void addVat(std::vector<double>& prices) {
for (double& p : prices) { p *= 1.2; } // works
}
void broken(std::vector<double>& prices) {
for (double p : prices) { p *= 1.2; } // edits a copy each iteration
}
And beware bare auto: it strips references, so for (auto p : prices) copies. Write auto& to modify, const auto& to read.
Multiple outputs
Reference parameters are the traditional way to return more than one value. Prefer a struct when the values belong together, and keep references for a genuinely secondary result:
bool parseDate(const std::string& text, int& day, int& month, int& year); // acceptable
std::optional<Date> parseDate(const std::string& text); // better
Real World Example: An Inventory Adjuster
A stock system that reads, modifies and reports — each function picking its parameter style deliberately.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stdexcept>
struct Product {
std::string name;
int quantity;
double unitPrice;
};
// Read-only, and the struct owns a string -> const reference.
void print(const Product& p) {
std::cout << p.name << ": " << p.quantity
<< " @ " << p.unitPrice << "\n";
}
// Read-only over the whole container -> const reference. No copy of any product.
double stockValue(const std::vector<Product>& stock) {
double total = 0.0;
for (const Product& p : stock) {
total += p.quantity * p.unitPrice;
}
return total;
}
// The job IS to modify -> non-const reference. Small numbers by value.
void restock(Product& p, int extra) {
p.quantity += extra;
}
// Modifies every element in place. Note 'Product&' in the loop.
void applyPriceRise(std::vector<Product>& stock, double percent) {
const double factor = 1.0 + percent / 100.0;
for (Product& p : stock) {
p.unitPrice *= factor;
}
}
// Returns a reference into a container the caller owns -- safe, because
// the caller's vector outlives the call. Aborts if the name is absent.
Product& findByName(std::vector<Product>& stock, const std::string& name) {
const auto it = std::find_if(stock.begin(), stock.end(),
[&name](const Product& p) { return p.name == name; });
if (it == stock.end()) {
throw std::runtime_error("No such product: " + name);
}
return *it;
}
// Two outputs, only one of which is the point -> reference for the extra.
int countLowStock(const std::vector<Product>& stock, int threshold,
std::string& worstName) {
int count = 0;
int worst = threshold + 1;
worstName.clear();
for (const Product& p : stock) {
if (p.quantity < threshold) {
++count;
if (p.quantity < worst) { worst = p.quantity; worstName = p.name; }
}
}
return count;
}
int main() {
std::vector<Product> stock{
{"Widget", 40, 2.50},
{"Gasket", 3, 0.80},
{"Flange", 12, 7.25}
};
std::cout << "Value: " << stockValue(stock) << "\n";
restock(findByName(stock, "Gasket"), 50); // reference feeds a reference
applyPriceRise(stock, 10.0);
std::string worst;
const int low = countLowStock(stock, 20, worst);
std::cout << low << " low line(s), worst is " << worst << "\n";
for (const Product& p : stock) { print(p); }
std::cout << "Value: " << stockValue(stock) << "\n";
return 0;
}
Every signature above is a decision. print and stockValue take const& because Product owns a std::string — passing by value would allocate once per product, and stockValue over a thousand-line inventory would allocate a thousand times for no reason. restock takes Product& without const precisely because mutation is its purpose; the name and the signature agree, so a reader is not surprised. Its int extra stays by value because copying an int is free and a reference would just add a dereference. applyPriceRise uses Product& in the range-based loop rather than Product — with the ampersand omitted it would dutifully multiply a copy and change nothing, which is the single most common reference bug in the language. findByName returns Product& safely because the referent lives in the caller's vector, not in a local; that is what makes the composed call restock(findByName(stock, "Gasket"), 50) legal, and it would be undefined behaviour if the function had built its own local Product. Finally countLowStock returns the count and reports the worst offender through std::string& worstName: the count is the answer, so it is the return value, while the name is a secondary diagnostic — had both been equally important, a small struct would have been the better shape.
Common Mistakes
- Forgetting the
&in a modifying function.void reset(int n) { n = 0; }compiles, runs, and does nothing. Silent, and easy to miss. - Forgetting the
&in a range-basedfor.for (Product p : stock)copies each element; edits are discarded and large structs are copied needlessly. - Omitting
conston read-only parameters. It hides intent and rejects literals and temporaries at the call site. - Passing small types by reference.
void f(const int& n)is not an optimisation; it is one more indirection. - Holding a reference across a container growth.
push_backmay reallocate and leave your reference dangling. - Returning a reference to a local. The object dies at the closing brace. Only return references to things that outlive the call.
- Using
T&when the argument may be absent. References cannot be null. Take a pointer and check it. - Piling up output parameters. Four
int¶meters is a struct waiting to be written.
Best Practices
- Default to
const T&for anything bigger than two machine words, and plainTfor anything smaller. - Use non-
constT&only when modifying is the function's stated job, and name the function so a reader expects it (restock,normalise,applyPriceRise). - Write
auto&orconst auto&in range-based loops. Bareautocopies. - Take references late and briefly. Do not store one across operations that can reallocate.
- Prefer returning a value or a struct to filling several output parameters.
- Use
std::string_viewfor read-only text parameters when you do not need to own or store the string. - Reach for
T*only for optional arguments, and check for null on entry.
Practice Exercises
- Break it then fix it: Write
void addBonus(std::vector<double> scores, double bonus)that adds the bonus to every score, print the vector before and after, and confirm nothing changed. Add one ampersand and confirm it now works. Explain in a comment why the compiler never warned you. - Swap without a temporary variable name clash: Write
void swapProducts(Product& a, Product& b)for the struct above, then compare your version withstd::swap. Verify that swapping a product with itself still leaves it intact. - Catch a dangler: Take a reference to
stock[0],push_backtwenty more products, then write through the reference. Build withg++ -fsanitize=addressand paste the report into a comment. Fix it by storing an index instead of a reference. - Const-correctness pass: Write a
Reportstruct holding astd::stringtitle and astd::vector<double>of 100000 readings, give it a copy constructor that prints "COPY", and pass it todouble average(Report r)andvoid rename(Report r, const std::string& title). Count the copies, then convert each parameter to the narrowest form that still works —const Report&for one,Report&for the other — and count again. Finish by trying to callrenameon aconst Report, and explain in a comment what the error is telling you about the function's intent.