References
A reference is another name for an object that already exists. After int& r = n;, r and n are the same object: writes through one are visible through the other, and a reference cannot be reseated.
Detailed Explanation
You are writing a function that updates a running total. Passing the total by value gives the function a copy, so the caller's number never changes. Passing a pointer works, but now every use needs * and every caller worries about null. A reference is the third option: the parameter is an alias for the caller's object.
A reference is not a second object. It is a name. The declaration int& r = n; means "from now on, r means n". There is no separate storage you are supposed to think about. Implementations often use a pointer under the hood, but the language does not let you observe that pointer or make the reference point somewhere else later.
That last rule is the whole design. A pointer can be null, can be incremented, and can be reassigned. A reference cannot do any of those. It is bound at initialisation and stays bound. That is why function parameters that must refer to an existing object are references, and why operator[] on std::vector returns a reference: the caller is naming an element, not receiving a copy.
There are two everyday flavours. An lvalue reference (T&) binds to an object that already has a name. A const lvalue reference (const T&) also binds to temporaries, which is why void print(const std::string& s) can accept both a variable and the temporary from std::string("hi"). The temporary lives for the whole call. An rvalue reference (T&&) binds to a temporary or an object you have cast with std::move, and is the hook that move constructors hang from.
References appear in three places you will use every day:
- Function parameters.
void add(int& total, int n)mutates the caller.void show(const std::string& s)avoids a copy without allowing mutation. - Function return types.
int& operator[](size_t i)hands back an element you can assign to. Returning a reference to a local variable is a dangling reference and undefined behaviour. - Range-for.
for (auto& item : items)bindsitemto each element so you can edit the container in place.
A reference to a pointer (int*&) is a thing, and so is a pointer to a... no. You cannot have a pointer to a reference, an array of references, or a reference to a reference in the source you write. Reference collapsing in templates is a separate rule that turns T& & into T&.
The cost of a reference parameter versus a pointer parameter is the same at the machine level. The cost you save is the copy you did not make. Passing a 32-byte std::string by value copies the control block and may copy the heap buffer; passing const std::string& copies a pointer-sized alias.
Code Examples
#include <iostream>
#include <string>
void addTax(double& price, double rate) {
price *= (1.0 + rate); // writes the caller's variable
}
void label(const std::string& name) {
// name is an alias; the caller still owns the string
std::cout << "user=" << name << '\n';
}
int main() {
double cart = 40.0;
addTax(cart, 0.10);
std::cout << cart << '\n'; // prints: 44
std::string who = "ada";
label(who);
label(std::string("tmp")); // const& binds to the temporary
}#include <vector>
int& first(std::vector<int>& v) {
return v.front(); // alias into the vector
}
int main() {
std::vector<int> scores{10, 20};
first(scores) = 99; // scores[0] is now 99
}Common Gotchas
A reference must be initialised
`int& r;` does not compile. There is no "null reference" you can declare and bind later.
Returning a reference to a local
`int& f() { int x = 1; return x; }` leaves the caller with a name for storage that has been destroyed. Use return-by-value, or return a reference to something the caller already owns.
`auto&` versus `auto`
`for (auto x : v)` copies each element. `for (auto& x : v)` edits in place. `for (const auto& x : v)` is the default for anything heavier than a machine word that you only read.
reseating is assignment through the reference
after `int& r = a; r = b;`, `a` now holds `b`'s value. `r` still names `a`. To change which object you talk about, use a pointer.