Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. A second name for the same object
    4. A reference must start bound
    5. A reference stays bound to one object
    6. Passing arguments by reference
    7. Reading big objects with const T&
    8. Loops that change elements: auto&
    9. Which one should I use?
    10. Under the hood
    11. Common pitfalls
    12. Returning a reference to a local variable
    13. Keeping a reference into a vector while it grows
    14. Try it yourself

    Module 2 · Memory

    2.2References

    A reference is a second name for an object that already exists. Use one to let a function change your variable, or to read a big object without copying it, and learn the one way a reference goes wrong.

    About 20 minutesBeginner

    On this page
    1. Key terms
    2. In 30 seconds
    3. A second name for the same object
    4. A reference must start bound
    5. A reference stays bound to one object
    6. Passing arguments by reference
    7. Reading big objects with const T&
    8. Loops that change elements: auto&
    9. Which one should I use?
    10. Under the hood
    11. Common pitfalls
    12. Returning a reference to a local variable
    13. Keeping a reference into a vector while it grows
    14. Try it yourself

    Key terms

    reference (T&)
    Another name for an object that already exists. Reading or changing the reference reads or changes that object.
    bind
    To attach a reference to its object. It happens once, when the reference is created, and can't be changed later.
    const T&
    A reference you can read through but not change through. The usual way to pass a big object to a function.
    pass by value
    The function gets its own copy of the argument. Changing it doesn't touch the caller's variable.
    pass by reference
    The function gets a reference to the caller's object, so no copy is made.
    dangling reference
    A reference whose object no longer exists. Using it is undefined behavior.

    When you assign one int to another, C++ copies the value. Often that’s what you want. But sometimes a function needs to change the caller’s variable, or an object is too big to copy every time you pass it. A reference solves both: it’s a second name for an object that already exists, so nothing is copied.

    In 30 seconds

    • int& r = x; makes r another name for x. Changing r changes x.
    • A reference must be bound to an object when it’s created, and it stays bound to that object.
    • Pass T& when a function should change its argument, and const T& when it only reads a big one.
    • A reference doesn’t keep its object alive. If the object goes away first, the reference dangles.

    A second name for the same object

    Put & after the type to declare a reference. From then on, the reference and the original are the same object: there’s one int here, with two names.

    #include <print>
    
    int score = 10;
    int& alias = score;
    alias += 5;
    std::println("{} {}", score, alias);

    Output

    15 15
    After int& alias = scoreOn the stack, score holds the value 15. alias holds no value of its own: an arrow from alias points at score, because alias is another name for score.Stackscore: intvalue15alias: int&refers to
    After int& alias = score. On the stack, score holds the value 15. alias holds no value of its own: an arrow from alias points at score, because alias is another name for score.

    A reference must start bound

    A reference with nothing to refer to makes no sense, so C++ doesn’t allow one:

    int value = 5;
    int& r;

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:2:6: error: ‘r’ declared as reference but not initialized
        2 | int& r;
          |      ^

    A reference stays bound to one object

    Once bound, a reference stays bound. Assigning to it assigns to its object; it doesn’t make the reference point somewhere else:

    #include <print>
    
    int a = 1;
    int b = 2;
    int& r = a;
    r = b; // copies b's value into a; r still refers to a
    b = 3;
    std::println("{} {} {}", a, b, r);

    Output

    2 3 2

    Key ideaSame object, two names

    A reference isn’t a copy and isn’t a separate variable you can repoint. Whatever you do to the reference, you do to the object it was bound to.

    Passing arguments by reference

    By default, C++ passes arguments by value: the function gets its own copy. Changing the copy leaves the caller’s variable alone. Give the parameter a reference type and the function works on the caller’s object instead.

    #include <print>
    
    void add_bonus_to_copy(int points) {
        points = points + 10; // changes the copy only
        std::println("inside: {}", points);
    }
    
    void add_bonus(int& points) {
        points = points + 10; // changes the caller's variable
    }
    
    int main() {
        int score = 50;
        add_bonus_to_copy(score);
        std::println("after copy: {}", score);
        add_bonus(score);
        std::println("after reference: {}", score);
    }

    Output

    inside: 60
    after copy: 50
    after reference: 60

    Reading big objects with const T&

    Copying an int is free, but copying a std::vector with a million elements isn’t. When a function only reads its argument, take it by const reference: no copy, and the compiler stops the function from changing it.

    #include <print>
    #include <string>
    #include <vector>
    
    double average(const std::vector<double>& values) {
        double total = 0.0;
        for (double v : values) {
            total += v;
        }
        return total / static_cast<double>(values.size());
    }
    
    void greet(const std::string& name) {
        std::println("Hello, {}!", name);
    }
    
    int main() {
        std::vector<double> readings = {2.5, 3.5, 6.0};
        std::println("{}", average(readings));
        greet("Ada");
    }

    Output

    4
    Hello, Ada!

    greet("Ada") works because a const reference can also bind to a temporary object: C++ builds a std::string from "Ada", and keeps it alive until the call ends.

    Changing an object through a const reference is a compile error:

    int total = 0;
    const int& view = total;
    view = 10;

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:3:6: error: assignment of read-only reference ‘view’
        3 | view = 10;
          | ~~~~~^~~~

    Loops that change elements: auto&

    The same rule applies in a range for loop. for (int x : v) gives you a copy of each element; for (auto& x : v) gives you the element itself.

    #include <print>
    #include <vector>
    
    std::vector<int> counts = {1, 2, 3};
    for (auto& c : counts) {
        c *= 10;
    }
    std::println("{}", counts);

    Output

    [10, 20, 30]

    Modern C++Printing a whole vector

    Since C++23, std::println("{}", v) prints a vector, a map or any other range directly, with brackets and commas. Older code loops over the elements instead.

    Which one should I use?

    WhatWhenWhyHow
    By value (T)Small types like int, double, char and bool, or when the function needs its own copy anyway.Copying a few bytes is as cheap as passing a reference, and the caller’s variable stays safe.void f(int n)
    By const reference (const T&)The function only reads a large object: a std::string, a std::vector, your own big struct.No copy is made, and the compiler guarantees the function can’t change it.void f(const std::string& s)
    By reference (T&)The function’s job is to change the caller’s object.The change is visible to the caller, with no copy.void f(std::vector<int>& v), called as f(v)

    Rule of thumb: pass small things by value and big things by const T&. Use a plain T& only when changing the argument is the point of the function; its name should say so, like add_bonus or sort_in_place.

    Under the hood

    A reference has no size of its own: sizeof on a reference gives the size of the object it refers to. But when the compiler needs to store a reference, such as a reference parameter or a reference inside a struct, it stores the object’s address, exactly like a pointer. On a 64-bit machine, that’s 8 bytes.

    #include <print>
    
    struct Holder {
        int& ref;
    };
    
    int main() {
        int value = 7;
        Holder h{value};
        std::println("{} {}", sizeof(int&), sizeof(Holder));
        std::println("{}", h.ref);
    }

    Output

    4 8
    7

    So passing a const std::vector<double>& costs the same as passing one pointer, however many elements the vector holds. That’s why it’s the default for reading big objects. The next lesson, Pointers, works with addresses directly.

    PerformanceDon't pass small types by const reference

    For an int or a double, const int& is no faster than int, and it can be slower: the function has to follow an address to read the value. Pass small types by value.

    Common pitfalls

    A reference doesn’t own its object or keep it alive. If the object is destroyed while the reference is still around, the reference dangles, and using it is undefined behavior: the program might print garbage, crash, or seem to work.

    Returning a reference to a local variable

    A function’s local variables are destroyed when it returns, so a reference to one is dangling before the caller even gets it. GCC and Clang warn about this; with warnings as errors, it doesn’t compile:

    #include <print>
    
    const int& bigger(int a, int b) {
        int result = a > b ? a : b;
        return result;
    }
    
    int main() {
        std::println("{}", bigger(3, 7));
    }

    The compiler rejects this

    main.cpp: In function ‘const int& bigger(int, int)’:
    main.cpp:5:12: error: reference to local variable ‘result’ returned [-Werror=return-local-addr]
        5 |     return result;
          |            ^~~~~~
    main.cpp:4:9: note: declared here
        4 |     int result = a > b ? a : b;
          |         ^~~~~~
    cc1plus: all warnings being treated as errors

    The fix is to return by value: int bigger(int a, int b). Copying an int costs nothing.

    Keeping a reference into a vector while it grows

    std::vector stores its elements in one block of heap memory. When push_back needs more room than the block has, the vector allocates a bigger block, moves the elements there, and frees the old block. Any reference to an old element now refers to freed memory. The compiler can’t see this, so it compiles without a warning; the sanitizers catch it when the program runs:

    #include <print>
    #include <vector>
    
    std::vector<int> v = {1, 2, 3};
    int& first = v[0];
    v.push_back(4); // needs room for 4: moves the elements to a new block
    int copy = first;
    std::println("{}", copy);

    This fails when it runs

    ERROR: AddressSanitizer: heap-use-after-free on address 0x…
    READ of size 4 at 0x… thread T0
        #0 main main.cpp:7
    
    0x… is located 0 bytes inside of 12-byte region [0x…,0x…)
    freed by thread T0 here:
        #0 operator delete(void*, unsigned long)
           … 8 frames inside the standard library
        #9 main main.cpp:6
    
    previously allocated by thread T0 here:
        #0 operator new(unsigned long)
           … 6 frames inside the standard library
        #7 main main.cpp:4
    
    SUMMARY: AddressSanitizer: heap-use-after-free main.cpp:7 in main

    Undefined behaviorUndefined behavior isn't a crash you can count on

    Without sanitizers, this program often prints 1 and seems fine, because the freed memory still holds the old value. The bug shows up later, somewhere else. Build with -fsanitize=address,undefined while you learn; Setting up shows how.

    Common pitfallLook up the element again after changing the vector

    Keep an index (std::size_t i = 0;) instead of a reference, and write v[i] after any push_back, insert or erase. Or take the reference only after you’ve finished adding elements.

    Try it yourself

    Try it yourself

    This program should double every price, but it prints the prices unchanged. Fix scale so it changes the caller’s vector.

    #include <print>
    #include <vector>
    
    void scale(std::vector<double> values, double factor) {
        for (double x : values) {
            x *= factor;
        }
    }
    
    int main() {
        std::vector<double> prices = {1.5, 2.0, 4.25};
        scale(prices, 2.0);
        std::println("{}", prices);
    }

    Expected output

    [3, 4, 8.5]
    Show a hint

    There are two copies to remove: the vector is passed by value, so scale changes its own copy, and the loop variable is a copy of each element. Add & in both places.

    Show a solution
    #include <print>
    #include <vector>
    
    void scale(std::vector<double>& values, double factor) {
        for (double& x : values) {
            x *= factor;
        }
    }
    
    int main() {
        std::vector<double> prices = {1.5, 2.0, 4.25};
        scale(prices, 2.0);
        std::println("{}", prices);
    }

    std::vector<double>& values makes the function work on the caller's vector, and double& x makes each step of the loop work on one of its elements. With either & missing, prices stays unchanged.

    Saved in this browser only.