std::optional
std::optional<T> is a value that may hold a T or hold nothing. It replaces "pointer that might be null" and "sentinel such as -1" when the absence of a result is a normal outcome, not a crash.
Detailed Explanation
You look up a user by email. The user might not exist. Returning a User forces you to invent an empty User. Returning a User* forces a heap allocation or a pointer into a container that might reallocate. Returning std::optional<User> says "zero or one User, owned by the return value".
std::optional<T> is a wrapper with a boolean and a T (the T is constructed only when the optional is full). It is a regular value: you copy it, move it, return it, store it in a vector. It is not a pointer. There is no heap allocation unless T itself allocates.
Create an empty optional with std::nullopt or {}. Create a full one with std::optional<T>{value}, std::make_optional(value), or assignment from a T. has_value() and the contextual conversion to bool test fullness. * and -> reach the T and are undefined behaviour if the optional is empty. value() returns the T or throws std::bad_optional_access. value_or(fallback) returns the T or a copy of the fallback.
Use optional when absence is expected. A config key that might be missing, a find that might miss, a parse that might reject the input. Do not use it for "this function failed because the disk is on fire". That is an exception or an error type. Do not use it for a nullable owning heap object; that is still unique_ptr. Do not use optional<T&>. References are not objects the optional can store; C++26 discusses optional<T&> but C++17/20/23 do not have it. Use a pointer for a non-owning maybe-present object.
optional composes. optional<int> in a struct is a field that might be unset. A vector of optionals is usually a smell; a sparse map is clearer. Returning optional<T> from a function that already throws on other failures is fine: empty means "not found", throw means "the store is broken".
Comparisons treat empty as less than any full value, and two empties as equal. optional<T> compares to T and to nullopt. If T has operator==, you can write opt == 3.
Cost: one extra byte plus padding for the flag, next to a T. For a double that may mean 16 bytes total. For a large T, you pay sizeof(T) even when empty, because the storage is inline. If empty is the common case and T is huge, store unique_ptr<T> instead.
C++23 added monadic helpers: and_then, transform, or_else. They chain without nested if (opt). On C++17/20, write the if.
Code Examples
#include <iostream>
#include <optional>
#include <string>
#include <vector>
std::optional<int> findAge(const std::vector<std::pair<std::string, int>>& rows,
const std::string& name) {
for (const auto& [who, age] : rows) {
if (who == name) return age;
}
return std::nullopt;
}
int main() {
std::vector<std::pair<std::string, int>> rows{{"ada", 36}, {"al", 46}};
if (auto age = findAge(rows, "ada")) {
std::cout << *age << '\n'; // prints: 36
}
std::cout << findAge(rows, "grace").value_or(-1) << '\n'; // prints: -1
}#include <optional>
#include <string>
struct Config {
std::optional<std::string> proxy; // unset means "no proxy"
};
int main() {
Config cfg;
cfg.proxy = "http://localhost:8080";
cfg.proxy.reset(); // back to empty
}Common Gotchas
Dereferencing an empty optional is undefined behaviour
`*opt` and `opt->` do not throw. Use `if (opt)`, `value()`, or `value_or`.
`optional<bool>` and `optional<int>` in boolean context
`if (opt)` tests engagement, not the contained value. A full `optional<bool>{false}` is still true as a condition. Write `if (opt && *opt)`.
`value_or` returns by value
`opt.value_or(fallback)` copies. For a large `T`, branch on `has_value()` and use `*opt`.
Do not store `T&`
use `T*` for a non-owning maybe, or `std::reference_wrapper<T>` inside the optional if you need the optional API.