Pointers and References

Pointers and References

Understand addresses, indirection, aliasing, and when references are safer than raw pointers.

Pointers and References

Reference basics

int value = 10;
int& ref = value;
ref = 20;

Changing ref changes value because they refer to the same object.

Pointer basics

int value = 10;
int* ptr = &value;
*ptr = 20;

Null pointers

Use nullptr, not NULL or 0.

int* ptr = nullptr;

When to use what

Example

void increment(int& x) {
    ++x;
}

Warning signs

Ownership vs observation

Pointers and references often mean "I can access this object", not "I own it". In modern C++, ownership should usually be represented by:

const correctness

void print(const std::string& text);
void mutate(std::string& text);

When you add const accurately, both humans and the compiler get a stronger picture of what a function may change.

Safer view types

Modern C++ often replaces raw pointer-and-length pairs with std::span<T> and raw C strings with std::string_view.