On this page
  1. std::optional
  2. Overview
  3. Notes & Pitfalls
  4. Example

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

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