Lesson content
Read, practise, then check your understanding
A pointer stores an address and may be nullptr; dereferencing a null, dangling, or invalid pointer is undefined behavior. A reference is an alias that must bind at initialization and cannot be reseated. Neither form implies ownership by itself.
void increment(int& value) { ++value; }
int value{10};
int* pointer{&value};
if (pointer != nullptr) {
*pointer += 2;
}
increment(value);
const int* points to a read-only integer, int* const is a fixed pointer to mutable integer, and const int* const fixes both. Keep constness close to the contract.
Arithmetic, arrays, and lifetime
Pointer arithmetic is defined only within an array object (including one-past-the-end) and advances in units of the pointed type. Prefer iterators or std::span because they carry stronger range meaning. A pointer or reference dangles when its object dies, moves in a way that invalidates it, or a container reallocates.
Pointers to functions
int add(int a, int b) { return a + b; }
using Operation = int (*)(int, int);
Operation operation{&add};
int result = operation(3, 4);
Function pointers enable callbacks but cannot hold captured lambdas. Templates avoid type erasure; std::function can hold diverse callables at some runtime cost. Use references for required objects, pointers for optional non-owning access, and values, containers, or smart pointers to express ownership.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.