stl · medium

std::optional

std::optional<T> models 'maybe a value' as a first-class state instead of a sentinel like -1 or nullptr. It stores the T inline next to a bool, so engaging it allocates nothing on the heap. Access has three flavours: value() is checked and throws std::bad_optional_access when empty; operator* and operator-> are unchecked and are UB on an empty optional (guard with if(o) first); value_or(fallback) returns a default and never throws. The monadic operations and_then, transform and or_else (C++23) compose computations that run only while the optional is engaged and short-circuit to nullopt the moment it is empty.

🔑 Key line

std::optional<T> stores a T inline plus a bool (no heap): value() is checked and throws bad_optional_access when empty, operator*/-> are unchecked (UB on empty), value_or gives a safe fallback, and monadic and_then/transform/or_else chain while short-circuiting on nullopt.

The code

std::optional<int> o = 42; // engaged: holds a value, inline (no heap)
std::optional<int> e; // disengaged: empty (== std::nullopt)
if (o) use(*o); // contextual bool; * and -> are UNCHECKED
int a = e.value(); // checked: throws bad_optional_access if empty
int b = e.value_or(-1); // safe fallback when empty -> -1
auto r = o.and_then(half) // monadic (C++23): runs only if engaged,
.transform(sq); // short-circuits on nullopt

What this lesson walks through

  1. 01Engaged: it holds a value
  2. 02Disengaged: empty (nullopt)
  3. 03value() is checked — it throws
  4. 04value_or: a safe fallback
  5. 05operator* / -> are UNCHECKED
  6. 06Monadic chaining (C++23)
  7. 07Empty short-circuits the whole chain

std::optional<T> is a 'maybe a T'. When engaged it stores a real T inline, right next to a bool — no heap allocation. has_value() is true and the value is live.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of std::optional and 100+ animated C++ interview lessons.

← Previous
Small String Optimization (SSO)
Next →
Open Addressing — Cache-Friendly Hash Maps