std::optional — value that may or may not exist.
1#include <optional>23std::optional<int> divide(int a, int b) {4 if (b == 0) return std::nullopt;5 return a / b;6}78auto result = divide(10, 3);9if (result) {10 std::cout << *result;11}
Benefits:
Operations:
has_value(): check existencevalue(): get with exceptionvalue_or(default): get with fallback*opt: dereference (UB if empty)Use when: