Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 171 ยท Pointers, References and Memory

References

Learn C++ references - lvalue references as aliases, references as parameters and return values, const references binding temporaries, and dangling pitfalls.

A reference is another name for an object that already exists. When you write int& r = x;, you don't create a new integer: r is x, under a second name. Reading r reads x, assigning to r assigns to x, and taking the address of r gives the address of x.

That sounds like a small feature, but references are one of the pillars of C++. They let functions modify their arguments, let you pass a large std::vector without copying it, let operator[] return something you can assign to, and make range-based for loops able to change elements. This lesson covers how references behave, how to use them in parameters and return values, how const references can bind to temporaries, and the dangling-reference mistakes that every C++ programmer learns to avoid. It also sets you up for the next lesson, Pointers, by comparing the two.

Declaring a reference

Put & after the type to declare an lvalue reference. A reference must be initialized when it's declared, and from then on it always refers to the same object.

C++ A reference is another name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last two statements show the most important rule: a reference can't be reseated. alias = other; doesn't make alias refer to other. It assigns the value of other to the object alias already names, so score becomes 7.

A few more rules follow from "a reference is just a name":

  • No uninitialized references. int& r; is a compile error. There's nothing for it to name.
  • No null references. A valid reference always refers to an object. (You can create a broken one through undefined behavior, but no valid program has one.)
  • No references to references, no arrays of references. int& & r and int& refs[3] don't compile. Use std::reference_wrapper (std::ref) if you need to store references in a container.
  • The & binds to the name, not the type. In int& a = x, b = y;, only a is a reference; b is a plain int. Declare one reference per line.

What can a non-const reference bind to?

An int& binds only to an lvalue of type int: something with a name and an address that will stick around, like a variable, an array element or *ptr. It refuses temporaries and values of other types:

C++
int x = 3;
int& ok = x;          // fine: x is an lvalue int
int& bad1 = 42;       // error: 42 is a temporary
int& bad2 = x + 1;    // error: x + 1 is a temporary
double d = 2.5;
int& bad3 = d;        // error: d is not an int

The refusal is a safety feature. If int& r = 42; were allowed, you could write r = 5; and change... what, exactly? A temporary that's about to disappear. C++ forbids it so the mistake can't happen.

References as function parameters

By default, C++ passes arguments by value: the function gets a copy. A reference parameter makes the parameter an alias for the caller's variable, so the function can change it. The classic demonstration is swap:

C++ Changing the caller's variables through references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice that the call site swap_values(left, right) looks exactly like a call by value. Only the function's signature tells you the arguments can change. That's why the convention is strict:

  • T& means "this function may modify your object". Use it for in/out parameters.
  • const T& means "I only read it, and I don't want to copy it". Use it for large read-only objects such as std::vector, std::map or user-defined classes.
  • Plain T (by value) for small, cheap types like int, double, char, pointers, std::string_view and std::span, and when the function wants its own copy anyway.

The Parameters lesson goes deeper into these choices and why returning values usually beats output parameters.

References in range-based for

The same rule applies to loop variables. for (auto x : v) copies each element; for (auto& x : v) names each element directly, so changes stick; for (const auto& x : v) reads elements without copying them.

C++ Copy vs reference in a range-based for

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first loop doubles copies that are thrown away, so prices stays [100, 250, 75]. The second really doubles the elements to [200, 500, 150].

const references and temporaries

A reference to const (const T&) promises not to change the object through that name. It also gets one special power: it can bind to temporaries and to values that need a conversion. When that happens, C++ creates the temporary and extends its lifetime to match the reference.

C++ const references bind to temporaries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

This is why const std::string& parameters accept literals: the compiler builds a temporary std::string for the duration of the call. (For read-only text, std::string_view avoids even that temporary.)

Lifetime extension only works once, directly. It applies when a temporary is bound straight to a local const T& (or T&&). It does not carry through function calls. If a function takes a const T& and returns it, and you call it with a temporary, the temporary still dies at the end of the full expression and the returned reference dangles. const auto& x = std::max(1, 2); is a classic example: std::max returns a reference to one of its temporary arguments.

Returning references

A function can return a reference to give the caller direct access to an object that lives somewhere else: an element inside a container, a member of an object, or a parameter that was itself passed by reference. That's how std::vector::operator[] lets you write v[2] = 10;.

C++ Returning a reference to an element

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

find_leader uses a pointer internally because it needs to change which player it refers to while searching, something a reference can't do. That's a common pattern: pointers for "which one?", references for "this one". (Calling front() on an empty vector is undefined behavior; a real version would check first or return std::optional.)

Never return a reference to a local

The one deadly mistake is returning a reference to something that dies when the function returns:

C++
const std::string& broken_label() {
    std::string label = "temporary";
    return label;   // warning: reference to local variable 'label' returned
}                   // label is destroyed here; the caller gets a dangling reference

GCC warns about this case (-Wreturn-local-addr), but it can't catch every variant, for example a reference into a local vector or a member of a temporary object. The rule: return a reference only to objects that outlive the call. If the function creates the value, return it by value; copy elision and move semantics make that cheap (see Returning Values).

The same danger applies to references you store. A reference into a std::vector element becomes dangling if the vector reallocates:

C++
std::vector<int> v{1, 2, 3};
int& first = v[0];
v.push_back(4);        // may move all elements to new memory
first = 10;            // undefined behavior if it did

References vs pointers

References and pointers both let you reach an object indirectly, and under the hood a compiler usually implements a reference as a hidden pointer. The difference is in the rules the language enforces:

Reference T& Pointer T*
Must be initialized yes no (but you should)
Can be null no yes (nullptr)
Can be changed to refer elsewhere no yes
Syntax to use the object just the name *p or p->member
Can do arithmetic no yes (within arrays)
Can be stored in containers no (use std::reference_wrapper) yes

The guideline is simple: use a reference when there is always exactly one object and it never changes; use a pointer when "no object" is a valid answer or when you need to point at different objects over time. For optional parameters in modern code, T* (nullable) or std::optional<T> (owning a value) express "maybe" more clearly than any trick with references.

You'll also meet T&&, an rvalue reference. It binds to temporaries and is the basis of move semantics, covered in Move Semantics. In templates, auto&& and T&& act as "forwarding references" that can bind to anything. For now, T& and const T& are what you need.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. int a = 1, b = 2; int& r = a; r = b; r = 5; What are a and b afterwards?

    References can't be reseated. r = b copies 2 into a, then r = 5 sets a to 5. b is never touched.
  2. 2. Which declaration does NOT compile?

    A non-const lvalue reference can't bind to a temporary like 10. A const reference can, and the temporary's lifetime is extended.
  3. 3. std::vector<int> v{1, 2, 3}; for (auto x : v) { x = 0; } What does v contain afterwards?

    auto x makes a copy of each element, so the assignments change the copies. Use auto& x to modify the elements.
  4. 4. Why is returning a reference to a local variable a bug?

    Using the returned reference reads an object whose lifetime has ended, which is undefined behavior. GCC warns, but only for the obvious cases.
  5. 5. When is a pointer a better choice than a reference?

    References are never null and can't be reseated. Size and const-ness are handled equally well by const references.

Summary

  • A reference (T& r = x;) is another name for an existing object. Everything you do to r happens to x.
  • References must be initialized, can't be null and can't be reseated; assigning to a reference assigns to the object.
  • T& parameters let a function modify the caller's object; const T& parameters avoid copies of large read-only objects; small types go by value.
  • In range-based for, use auto& to modify elements and const auto& to read them without copying.
  • const T& can bind to temporaries and extends their lifetime, but only when bound directly to a local reference.
  • Return references only to objects that outlive the call; never to locals. Stored references into containers can dangle after reallocation.
  • Use references for "always exactly this object", pointers when null or reseating is needed.

Next: Pointers, where you'll work with addresses directly using &, * and nullptr.