On this page
std::optional
Prev: std::unordered_map | Up: containers | Next: std::array
Rel: std::expected, std::variant
Ref: cppreference — std::optional
Tags: #public #prog #cpp #stdlib #containers #tier/core
Overview
std::optional<T> (<optional>, C++17) represents a value that may or may not be present (std::nullopt), stored inline on the stack with no dynamic allocation. Prefer it over sentinel values (-1, "") or nullable pointers for optional return values.
Notes & Pitfalls
- Always check
if (opt)before*opt: Dereferencing an emptystd::optionalis undefined behavior (use.value()to throw or.value_or(default)for safe fallback). - Zero heap allocation: Stores
Tinline alongside aboolflag.
Example
#include <cassert>
#include <optional>
#include <string>
std::optional<int> find_positive(int x) {
return x > 0 ? std::optional<int>{x} : std::nullopt;
}
int main() {
assert(find_positive(7).value_or(0) == 7);
assert(find_positive(-1).value_or(0) == 0);
}
Linked from
Related notes
- tuts/cpp/stdlib/containers/array Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/expected Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/unordered_map Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/variant Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib
- tuts/cpp/stdlib/containers/map shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/span shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/string shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/string_view shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/vector shared tags: #containers, #cpp, #prog, #stdlib, #tier