Representing Absence with optional
Avoid null pointers.
The Problem with Null
Returning a sentinel like -1 or a null pointer to mean "no value" is fragile and easy to misuse. std::optional<T> represents "a value, or nothing" explicitly. Include <optional>.
#include <iostream>
#include <optional>
int main() {
std::optional<int> maybe = 42;
std::cout << *maybe << "\n";
}An Empty Optional
Default-constructing an optional, or assigning std::nullopt, gives an empty one that holds no value.
#include <iostream>
#include <optional>
int main() {
std::optional<int> empty;
std::optional<int> also = std::nullopt;
std::cout << empty.has_value() << " " << also.has_value() << "\n";
}All lessons in this course
- Representing Absence with optional
- Accessing optional Values
- std::expected Basics
- Error Handling Patterns