Modern C++ • C++20 baseline
References, Pointers, and nullptr
Use references for required aliases and pointers when absence or reseating is meaningful.
A reference must bind to an object when initialized and cannot later be reseated. A pointer can be null and can be changed to refer elsewhere. Neither one owns memory by itself. Use nullptr rather than integer zero or the legacy NULL macro to represent a null pointer.
Key points
- Prefer a reference for a required function argument.
- Prefer a smart pointer for ownership; use a raw pointer for non-owning optional access when appropriate.
Example
#include <iostream>
void add_bonus(int& score) {
score += 5;
}
int main() {
int score = 10;
add_bonus(score);
int* optional_score = nullptr;
std::cout << score << ' ' << (optional_score == nullptr) << '\n';
}
What to expect
15 1
Practice exercise
Design one function that requires an object and another that accepts an optional object. Explain the parameter choices.
Key idea: Pointers and references describe access, not ownership; make lifetime and ownership explicit separately.