std::optional — a type that may or may not hold a value. Safer than nullptr or sentinel values.
1#include <optional>23std::optional<int> findValue(int key) {4 if (key == 42) return 100;5 return std::nullopt;6}78auto result = findValue(42);910if (result.has_value()) {11 std::cout << *result; // 10012}1314// Value or default15int val = result.value_or(0); // 1001617// Emplace18std::optional<std::string> opt;19opt.emplace("hello");2021// Reset22opt.reset(); // No value
Use cases: