Accessing optional Values
Use value_or and has_value.
Dereference Operator
The fastest way to read an optional is *opt, but only when you are sure it holds a value, there is no check.
#include <iostream>
#include <optional>
int main() {
std::optional<int> o = 10;
if (o) std::cout << *o << "\n";
}The value() Method
opt.value() returns the value, but throws std::bad_optional_access if the optional is empty. Use it when an empty optional is a real error.
#include <iostream>
#include <optional>
int main() {
std::optional<int> o;
try { std::cout << o.value() << "\n"; }
catch (const std::bad_optional_access&) { std::cout << "empty!\n"; }
}All lessons in this course
- Representing Absence with optional
- Accessing optional Values
- std::expected Basics
- Error Handling Patterns