The Analogy: The Nickname
A variable is a person with a name. A reference is a nickname for that same person. Call out either name and the same individual turns round. There is no second person, no copy, no forwarding address — just two labels on one thing.
Two rules follow directly from the analogy. You cannot give a nickname to nobody, so a reference must be attached to something the moment it is created. And a nickname cannot be transferred to a different person later — once &nick means Alice, it means Alice for the rest of its life.
That is the whole feature. It sounds slight, and it is the mechanism behind almost every well-written function signature in C++.
Syntax or Core Structure
#include <iostream>
#include <string>
#include <vector>
int main() {
int score{42};
int& alias = score; // alias IS score -- the & is part of the type
alias = 100;
std::cout << score << "\n"; // 100 -- changing one changes both
std::cout << &score << " " << &alias << "\n"; // identical addresses
// Must be initialised, and cannot be reseated
// int& broken; // ERROR: a reference must bind to something
int other{7};
alias = other; // this ASSIGNS 7 into score -- it does NOT rebind
std::cout << score << "\n"; // 7
// const reference: read-only view, no copy
const std::string message{"hello"};
const std::string& view = message;
// view += "!"; // ERROR: view is a read-only alias
// The main use: function parameters
auto addTax = [](double& price) { price *= 1.20; }; // modifies the caller's
double cost{100.0};
addTax(cost);
std::cout << cost << "\n"; // 120
// References into a container
std::vector<int> data{1, 2, 3};
int& first = data[0];
first = 99; // data is now {99, 2, 3}
return 0;
}
Read int& alias = score; as "alias has type reference to int, and it names score". The & binds to the type, not to the variable — int &a, b; declares one reference and one plain int, which is why the house style puts it next to the type.
Technical Depth: The Three Parameter Styles, and Dangling
Why const& is the default for reading
struct Record { std::string name; std::vector<int> history; };
void byValue(Record r); // deep-copies the string AND the whole vector
void byRef(Record& r); // no copy, and may modify the caller's data
void byConstRef(const Record& r);// no copy, cannot modify. The right default.
Record r{"Ada", {1, 2, 3, 4, 5}};
byConstRef(r); // costs one address, nothing else
For an int or a double, by value is fine and arguably faster — the value fits in a register and a reference would add an indirection. For anything larger than a couple of words, the copy is real work. The rule most codebases settle on:
| Parameter type | Use | Because |
|---|---|---|
int, double, char, bool | by value | cheaper than an indirection |
const std::string& | const reference | avoids an allocation per call |
const std::vector<T>& | const reference | avoids copying every element |
const MyStruct& | const reference | avoids copying every member |
| anything you must modify | Type& | the change must be visible to the caller |
| a copy you intend to mutate and keep | by value | states the intent, enables move |
const& also accepts temporaries
void print(const std::string& s) { std::cout << s; }
void modify(std::string& s) { s += "!"; }
print("a literal"); // fine: a temporary string binds to const&
modify("a literal"); // ERROR: cannot bind a non-const reference to a temporary
A const reference can bind to a temporary and extends its life to the end of the expression. A non-const reference cannot, because modifying something about to be destroyed is meaningless. This is why const& parameters accept literals and function results while Type& parameters demand a named variable.
Dangling references: the real danger
// BROKEN: returns a nickname for someone who has left the building
int& broken() {
int local{42};
return local; // local dies here -- the reference dangles
}
int& r = broken();
std::cout << r; // undefined behaviour
// BROKEN: the temporary vector is destroyed at the semicolon
const int& x = std::vector<int>{1, 2, 3}[0];
std::cout << x; // undefined behaviour
// BROKEN: reallocation invalidates references into a vector
std::vector<int> v{1, 2, 3};
int& first = v[0];
v.push_back(4); // may move the whole buffer
first = 99; // undefined behaviour -- first points at freed memory
// FINE: returning a reference to something that outlives the call
struct Box {
std::vector<int> items;
int& at(std::size_t i) { return items[i]; } // the Box owns it
};
A reference does not keep its target alive. If the thing it names is destroyed, moved, or reallocated, the reference is a loaded gun. The vector case is the one that catches people in real code: any operation that can grow a vector invalidates every reference, pointer and iterator into it.
References versus pointers
int a{1}, b{2};
int& ref = a; // must bind now, always valid, cannot be reseated
ref = b; // assigns b's VALUE into a
int* ptr = &a; // can be null, can be reseated, needs * to read
ptr = &b; // now points at b -- rebinding is legal
*ptr = 99; // writes through it
if (ptr) { } // can be checked
| Reference | Pointer | |
|---|---|---|
| Can be null | no | yes |
| Must be initialised | yes | no |
| Can be reseated | no | yes |
| Syntax to use | plain name | * to read, -> for members |
| Arithmetic | no | yes |
| Can be in a container | not directly | yes |
The design rule: use a reference when the thing must exist, a pointer when it might legitimately be absent. A pointer parameter is a signal to the reader that nullptr is a valid input and must be checked. Since C++17, std::optional covers many of the cases where a pointer used to mean "maybe".
auto and references
std::vector<std::string> names{"Ada", "Alan"};
auto a = names[0]; // COPY -- auto strips the reference
auto& b = names[0]; // reference to the element
const auto& c = names[0]; // read-only reference
for (auto x : names) { x += "!"; } // edits copies, names unchanged
for (auto& x : names) { x += "!"; } // edits the elements
for (const auto& x : names) { print(x); } // reads, no copies
Bare auto always deduces a value type, so it copies. If you want a reference you must write the & yourself — this is the most common source of accidental copies in modern C++.
Real World Example: A Shopping Basket
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
struct Item {
std::string name;
double unitPrice{0.0};
int quantity{0};
double lineTotal() const { return unitPrice * quantity; }
};
// const& : reads a whole vector of structs, copies nothing
double basketTotal(const std::vector<Item>& basket) {
double total{0.0};
for (const Item& item : basket) { // const Item& -- no copy per pass
total += item.lineTotal();
}
return total;
}
// Type& : must be visible to the caller
void applyDiscount(Item& item, double percent) {
item.unitPrice *= (1.0 - percent / 100.0);
}
// Two references out, one in -- an old-style but clear way to return two values
void findExtremes(const std::vector<Item>& basket,
const Item*& dearest, const Item*& cheapest) {
dearest = cheapest = &basket.front();
for (const Item& item : basket) {
if (item.lineTotal() > dearest->lineTotal()) { dearest = &item; }
if (item.lineTotal() < cheapest->lineTotal()) { cheapest = &item; }
}
}
// Returning a reference into a container the caller owns -- safe, it outlives us
Item& findByName(std::vector<Item>& basket, const std::string& name) {
for (Item& item : basket) {
if (item.name == name) { return item; }
}
return basket.front(); // a real design would use a pointer or optional
}
int main() {
std::vector<Item> basket{
{"Coffee beans", 8.50, 2},
{"Oat milk", 1.20, 6},
{"Sourdough", 3.75, 1},
};
std::cout << std::fixed << std::setprecision(2);
std::cout << "Before: " << basketTotal(basket) << "\n";
// Get a nickname for one item and edit it through the reference
Item& coffee = findByName(basket, "Coffee beans");
applyDiscount(coffee, 20.0);
coffee.quantity += 1;
// No copy: this alias reads the real element
const Item& bread = basket[2];
std::cout << bread.name << " is " << bread.lineTotal() << "\n";
const Item* dearest{nullptr};
const Item* cheapest{nullptr};
findExtremes(basket, dearest, cheapest);
for (const Item& item : basket) {
std::cout << std::setw(15) << std::left << item.name
<< item.quantity << " x " << item.unitPrice
<< " = " << item.lineTotal() << "\n";
}
std::cout << "Dearest line: " << dearest->name << "\n";
std::cout << "Cheapest line: " << cheapest->name << "\n";
std::cout << "After: " << basketTotal(basket) << "\n";
// The hazard, stated out loud:
// basket.push_back({"Butter", 2.10, 1});
// coffee, bread, dearest and cheapest may ALL dangle after this line.
return 0;
}
Each signature encodes an intention. basketTotal promises not to touch the basket, and copies nothing to prove it. applyDiscount takes Item& because a discount that vanished at the end of the function would be useless. findByName returns Item&, so the caller gets a live handle — coffee really is the element inside the vector, which is why editing it through the alias changes the basket. Where absence is possible, the code switches to pointers: dearest and cheapest start as nullptr and are reseated as the loop finds better candidates, something a reference could not do. And the commented-out push_back at the end is the lesson's core warning made explicit: every one of those handles is only valid while the vector's buffer stays put.
Common Mistakes
- Returning a reference to a local variable. It dies at the closing brace; the caller reads freed memory.
- Holding a reference across a
push_back. Reallocation invalidates it silently. - Expecting
ref = otherto rebind. It assigns a value into the original target. - Passing large structs by value out of habit. Every string and vector member is deep-copied.
- Forgetting
conston a read-only parameter, so callers cannot pass literals or temporaries. - Using
autoin a range-based loop when you meantauto&— you modify copies and nothing changes. - Using a reference where
nullptris a legitimate answer. Use a pointer orstd::optionalinstead. - Writing
int &a, b;and assuming both are references. Onlyais.
Best Practices
const Type&for reading,Type&for modifying, by value for small primitives. This one rule covers most signatures you will ever write.- Attach
&to the type, not the name:const std::string& s. - Never return a reference to a local, and never keep one to a vector element across an insertion.
- Prefer references to pointers when the target must exist; a pointer parameter tells the reader to expect null.
- Write
auto&orconst auto&deliberately — bareautoalways copies. - Mark member functions
constso they work throughconstreferences. - Return a struct rather than filling reference out-parameters when you have a choice; the call site reads better.
Practice Exercises
- Swap without a library: Write
void swap(int& a, int& b)using a temporary, then prove it works by printing the addresses of the caller's variables before and after. - Copy cost: Write a struct holding a
std::vector<int>of 100,000 elements. Pass it to an empty function a million times, once by value and once byconst&, timing both withstd::chrono. Report the ratio. - Break it deliberately: Take a reference to
v[0],push_backenough elements to force a reallocation, then write through the reference. Run it under-fsanitize=addressand record exactly what the sanitiser says.