std::optional is a class template in the <optional> header, added in C++17. An std::optional<T> either holds a value of type T or holds nothing. A function can return one to say that there may be no result. That is clearer than a sentinel value such as -1 or an empty string, either of which might also be a real answer.
What std::optional holds
An optional is either engaged, meaning it has a value, or empty, meaning it has none. std::nullopt is a constant that represents the empty state. You can assign it to an optional or return it from a function. An optional stores its value inside the object itself, so it does not allocate memory on the heap.
Creating and checking an optional
This program creates an optional with a value, an empty optional, and one set to std::nullopt, then checks each of them.
#include <iostream>
#include <optional>
int main() {
std::optional<int> a = 42; // holds a value
std::optional<int> b; // empty
std::optional<int> c = std::nullopt; // empty
if (a.has_value()) {
std::cout << "a = " << *a << "\n";
}
if (!b) {
std::cout << "b is empty\n";
}
std::cout << "c is " << (c.has_value() ? "set" : "empty") << "\n";
return 0;
}
Output:
a = 42
b is empty
c is empty
has_value() returns true when the optional holds a value. The conversion to bool is explicit, so if (opt) and !opt work. A plain assignment such as bool ok = opt; does not compile.
Reading the value safely
There are three common ways to get the value out:
*optandopt->give direct access. On an empty optional, they cause undefined behavior, so check first.opt.value()returns the value, or throwsstd::bad_optional_accessif the optional is empty.opt.value_or(fallback)returns the value, orfallbackif the optional is empty. It never throwsstd::bad_optional_access, which makes it a good choice when you have a sensible default.
The next program uses value_or to print a default when there is no nickname.
#include <iostream>
#include <optional>
#include <string>
std::optional<std::string> find_nickname(bool has_nickname) {
if (has_nickname) {
return std::string("Sam");
}
return std::nullopt;
}
int main() {
auto first = find_nickname(false);
std::cout << first.value_or("(none)") << "\n";
auto second = find_nickname(true);
std::cout << second.value_or("(none)") << "\n";
return 0;
}
Output:
(none)
Sam
Use value() when an empty optional is a mistake you want to catch. Catch std::bad_optional_access around the call:
std::optional<int> empty;
try {
std::cout << empty.value() << "\n";
} catch (const std::bad_optional_access&) {
std::cout << "no value\n";
}
Returning an optional from a function
An optional fits a function that may not find an answer. This program searches a vector and returns the index of a value, or nothing if the value is absent.
#include <cstddef>
#include <iostream>
#include <optional>
#include <vector>
std::optional<std::size_t> find_index(const std::vector<int>& values, int target) {
for (std::size_t i = 0; i < values.size(); ++i) {
if (values[i] == target) {
return i;
}
}
return std::nullopt;
}
int main() {
std::vector<int> numbers = {4, 8, 15, 16, 23, 42};
if (auto pos = find_index(numbers, 15)) {
std::cout << "Found 15 at index " << *pos << "\n";
}
if (!find_index(numbers, 7)) {
std::cout << "7 is not in the list\n";
}
return 0;
}
Output:
Found 15 at index 2
7 is not in the list
Returning -1 for “not found” works only if -1 can never be a real index, and nothing forces the caller to check for it. With an optional, the empty case is part of the return type. A caller that calls value() on an empty result gets an exception rather than a silent wrong answer.
Other tools in the header
std::make_optional(x)creates an optional from a value and deduces its type.reset()empties an optional.emplace(args...)replaces the current value by constructing a new one in place.- C++23 adds
and_then,transformandor_else, which chain operations on an optional without writing each empty check yourself.
Common mistakes
- Dereferencing an empty optional.
*and->on an empty optional are undefined behavior, not an exception. The program may crash later or appear to work. - Assuming
value()cannot fail. It throwsstd::bad_optional_accesson an empty optional, and an uncaught exception ends the program. - Expecting a reference. An optional stores its own copy of the value. If you need to refer to an object that lives somewhere else, a pointer or a reference fits better.
- Compiling with an older standard. Optional needs C++17. Some compilers default to an earlier standard, so pass the flag, for example
g++ -std=c++17 -Wall demo.cpp -o demo.
When to use std::optional
Use an optional when having no value is a normal result, such as a lookup that can find nothing or a setting the user may leave unset. If a value always exists, return it plainly. Pointers and references are the better fit when you need to refer to an object that lives somewhere else.
Try changing the inputs in the programs above to see both branches run.