References

References in C++: A variable is a person with a name. A reference is a nickname for that same person.

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 typeUseBecause
int, double, char, boolby valuecheaper than an indirection
const std::string&const referenceavoids an allocation per call
const std::vector<T>&const referenceavoids copying every element
const MyStruct&const referenceavoids copying every member
anything you must modifyType&the change must be visible to the caller
a copy you intend to mutate and keepby valuestates 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
ReferencePointer
Can be nullnoyes
Must be initialisedyesno
Can be reseatednoyes
Syntax to useplain name* to read, -> for members
Arithmeticnoyes
Can be in a containernot directlyyes

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 = other to 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 const on a read-only parameter, so callers cannot pass literals or temporaries.
  • Using auto in a range-based loop when you meant auto& — you modify copies and nothing changes.
  • Using a reference where nullptr is a legitimate answer. Use a pointer or std::optional instead.
  • Writing int &a, b; and assuming both are references. Only a is.

Best Practices

  1. const Type& for reading, Type& for modifying, by value for small primitives. This one rule covers most signatures you will ever write.
  2. Attach & to the type, not the name: const std::string& s.
  3. Never return a reference to a local, and never keep one to a vector element across an insertion.
  4. Prefer references to pointers when the target must exist; a pointer parameter tells the reader to expect null.
  5. Write auto& or const auto& deliberately — bare auto always copies.
  6. Mark member functions const so they work through const references.
  7. Return a struct rather than filling reference out-parameters when you have a choice; the call site reads better.

Practice Exercises

  1. 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.
  2. 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 by const&, timing both with std::chrono. Report the ratio.
  3. Break it deliberately: Take a reference to v[0], push_back enough elements to force a reallocation, then write through the reference. Run it under -fsanitize=address and record exactly what the sanitiser says.