Skip to content
LeetQuant
QD03 C++ Fundamentals

QD03 · C++ Fundamentals · Lesson 1 of 6

Values, Pointers and References

When C++ copies and when it aliases, how to choose between pass-by-value, reference and pointer, what const applies to, and how references and pointers dangle.

16 min

C++ copies by default

The objective of this lesson is to predict, for any line of C++, whether it makes a copy or creates an alias, and to pick the parameter type that says what a function does with its argument.

Python and Java give you references to objects almost everywhere. C++ does the opposite: a variable is the object, and assignment, initialisation and pass-by-value copy it. auto copy = v; on a std::vector allocates a new buffer and copies every element. To share an object you must ask for it explicitly with a reference (T&) or a pointer (T*).

  • A value T x owns its own storage. Changing it never affects anything else.
  • A reference T& r = x; is another name for an existing object. It must be initialised, can never be null, and can never be re-pointed ("reseated") at a different object. Assigning to r assigns to x.
  • A pointer T* p = &x; is an object that holds an address. It can be null (nullptr), can be reseated, and must be dereferenced (*p, p->member) to reach the object.
#include <iostream>
#include <vector>

void by_value(int x) { x += 1; }
void by_ref(int& x) { x += 1; }
void by_ptr(int* x) {
    if (x != nullptr) *x += 1;
}

int main() {
    int a = 10;
    by_value(a);
    std::cout << "after by_value: " << a << '\n';
    by_ref(a);
    std::cout << "after by_ref:   " << a << '\n';
    by_ptr(&a);
    std::cout << "after by_ptr:   " << a << '\n';
    by_ptr(nullptr);  // allowed, and handled

    std::vector<int> v{1, 2, 3};
    std::vector<int> copy = v;  // a new vector with its own buffer
    std::vector<int>& ref = v;  // another name for v
    copy.push_back(4);
    ref.push_back(5);
    std::cout << "v:    ";
    for (int x : v) std::cout << x << ' ';
    std::cout << "\ncopy: ";
    for (int x : copy) std::cout << x << ' ';
    std::cout << '\n';
}

Output (compiled with c++ -std=c++20 -O2 -Wall):

after by_value: 10
after by_ref:   11
after by_ptr:   12
v:    1 2 3 5
copy: 1 2 3 4

The same rule bites in range-for loops. for (auto o : orders) copies each element into o, so writing to o changes nothing and copying large elements costs time. Write for (const auto& o : orders) to read and for (auto& o : orders) to modify.

Choosing a parameter type

A function signature is documentation. The convention most C++ codebases (and interviewers) expect:

ParameterMeaningUse for
T xthe function gets its own copysmall, cheap types (int, double, pointers, small structs), or when the function would copy anyway
const T& xread-only access, no copylarge types you only read: std::string, std::vector, an Order struct
T& xthe function modifies the caller's objectout-parameters and in-place updates
T* xoptional object: nullptr means "none""may be absent", or interop with C APIs

A const T& parameter also binds to temporaries (f(std::string("ESZ6")) works), while a plain T& does not. Returning a pointer (or std::optional) is the idiomatic way to say "lookup may fail"; returning a reference promises that the object exists.

Two facts that come up in interviews:

  • A reference is not an object and has no address of its own; sizeof(T&) is sizeof(T). In practice the compiler implements a reference parameter as a pointer, so passing const T& costs one address, not a copy.
  • For int or double, const T& is not faster than T: the value fits in a register, and a reference forces the callee to load through memory and worry about aliasing. Pass small types by value.

const applies to the thing on its left

Read pointer declarations right to left. const qualifies what is immediately to its left (or, if nothing is to its left, what is immediately to its right).

#include <iostream>

struct Position {
    int qty = 0;
    int get() const { return qty; }  // const member: callable on a const Position
    void add(int q) { qty += q; }    // non-const: needs a mutable Position
};

int main() {
    int x = 1, y = 2;
    const int* p1 = &x;  // pointer to const int: *p1 is read-only
    p1 = &y;             // fine: the pointer itself can move
    int* const p2 = &x;  // const pointer to int: p2 cannot be reseated
    *p2 = 10;            // fine: the int it points to can change
    // *p1 = 3;          // error: read-only variable is not assignable
    // p2 = &y;          // error: cannot assign to variable 'p2' with const-qualified type
    const Position pos{5};
    // pos.add(1);       // error: 'add' is not marked const
    std::cout << *p1 << ' ' << x << ' ' << pos.get() << '\n';  // prints: 2 10 5
}

The three commented-out lines are rejected by the compiler with the errors shown (clang 17). const correctness means marking every reference parameter and member function const unless it must modify state. It documents intent, lets const objects call your methods, and turns accidental writes into compile errors. A const member function cannot modify members (except those declared mutable, which is how a const getter can lock a mutex or fill a cache).

Worked example

design the signatures for an order book helper

You hold a std::vector<Order> where Order has an id, a symbol string, a price and a qty. Write three functions: one that computes an order's notional, one that reduces an order's quantity after a fill, and one that finds an order by id when it may not exist. Choose each parameter and return type and justify it.

Show solution
  • notional only reads, and Order contains a std::string, so a copy would allocate. Take const Order&.
  • fill must change the caller's order, so take Order&. The fill size is an int, so pass it by value.
  • find may fail. Returning Order& would force us to throw or invent a sentinel; returning Order* lets nullptr mean "not found". It takes the vector by non-const reference because the caller will modify the order through the returned pointer.
#include <iostream>
#include <string>
#include <vector>

struct Order {
    long id;
    std::string symbol;
    double price;
    int qty;
};

// Read-only access to a large object: const reference, no copy.
double notional(const Order& o) { return o.price * o.qty; }

// Must modify the caller's object: non-const reference.
void fill(Order& o, int filled) { o.qty -= filled; }

// "Might not exist": pointer, nullptr means not found.
Order* find(std::vector<Order>& book, long id) {
    for (Order& o : book)
        if (o.id == id) return &o;
    return nullptr;
}

int main() {
    std::vector<Order> book{{1, "ESZ6", 5000.25, 10}, {2, "NQZ6", 18000.5, 3}};
    if (Order* o = find(book, 2)) {
        fill(*o, 1);
        std::cout << o->symbol << " qty " << o->qty << " notional " << notional(*o) << '\n';
    }
    if (find(book, 99) == nullptr) std::cout << "order 99 not found\n";
}

Output:

NQZ6 qty 2 notional 36001
order 99 not found

Check: after the fill the quantity is 3−1=23 - 1 = 2 and the notional is 18000.5×2=3600118000.5 \times 2 = 36001. Note the loop variable in find is Order& o; with Order o the function would return the address of a loop-local copy, which dies at the end of each iteration.

Dangling references and pointers

A reference or pointer does not keep its object alive. When the object's lifetime ends, every reference and pointer to it dangles, and using it is undefined behaviour: the program may print the old value, garbage, or crash, and the optimiser is allowed to assume it never happens.

The three classic sources:

  1. Returning a reference or pointer to a local. The local is destroyed when the function returns. Clang catches the simple case with -Wall:
const std::string& label() {
    std::string s = "local";
    return s;  // warning: reference to stack memory associated with local variable 's' returned
}
  1. Container reallocation. A std::vector stores elements in one contiguous buffer. When push_back exceeds the capacity it allocates a larger buffer, moves the elements and frees the old one, so every pointer, reference and iterator into the old buffer dangles:
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v{1, 2, 3};
    const int* before = v.data();
    std::cout << "capacity before: " << v.capacity() << '\n';
    v.push_back(4);
    std::cout << "capacity after:  " << v.capacity() << '\n';
    std::cout << (before == v.data() ? "same buffer" : "buffer moved") << '\n';
}
capacity before: 3
capacity after:  6
buffer moved

(The growth factor is implementation-defined; libc++ doubled here.) So int& first = v[0]; v.push_back(x); use(first); is a bug even though it often appears to work.

  1. Views of temporaries. std::string_view sv = std::string("ESZ6") + "C"; points into a temporary string destroyed at the end of the statement.

nullptr. Use nullptr, not 0 or NULL, for a null pointer. It has its own type (std::nullptr_t), converts to any pointer type and never to int, so overloads like f(int) and f(char*) resolve as you expect. Dereferencing a null pointer is undefined behaviour, not a guaranteed crash; check before you dereference whenever null is a legal value.

Knowledge check

int a = 1; int& r = a; r = 5; int b = r; b = 7; int* p = &b; *p += 1; What does printing a and b give?

Knowledge check

Given double x = 1, y = 2; const double* p = &x; which statement compiles?

Knowledge check

std::vector<Order> orders{{10}, {20}}; for (auto o : orders) o.qty = 0; What is orders[0].qty + orders[1].qty afterwards?

Key takeaways

  • Assignment, initialisation and pass-by-value copy in C++. Aliasing needs an explicit & or *.
  • Pass small types by value, large read-only objects by const T&, objects you modify by T&, and "may be absent" as T*.
  • const T* is a pointer to const data; T* const is a const pointer. Mark member functions const when they do not modify the object.
  • References and pointers never extend lifetimes. Returning one to a local, or holding one across a vector reallocation, dangles.
  • Use nullptr, and treat dereferencing null as undefined behaviour, not as a guaranteed crash.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).