Language[lang]

std::optional Explained: A Value or Nothing at All

Section
Language [lang]
Published
Length
14 min read
In this answer10 clauses
  1. 1Why Std::optional Exists in the First Place
  2. 1.1The trouble with magic values and flags
  3. 1.2Using unique_ptr and paying the heap cost
  4. 1.3When should you use std::optional?
  5. 2Creating and Initializing an Optional
  6. 2.1Starting with an empty optional
  7. 2.2Creating from a value or converting types
  8. 2.3Constructing the value directly in place
  9. 2.4How copying and moving an optional behaves
  10. 2.5Let make_optional deduce the type for you
  11. 3Checking Whether a Value Is Present
  12. 3.1Checking with has_value or an if test
  13. 4Reading the Value You Stored
  14. 4.1Checked reads with value that can throw
  15. 4.2Using * and -> like a pointer
  16. 4.3Falling back to a default with value_or
  17. 4.4Looping over an optional with iterators
  18. 5Changing, Assigning and Swapping an Optional
  19. 5.1Assigning a value, nullopt or another optional
  20. 5.2How to reset or emplace a std::optional?
  21. 5.3Swapping two optionals, empty or full
  22. 5.4Keeping the state safe when something throws
  23. 6Comparing and Chaining Optional Values
  24. 6.1How optionals stack up against values
  25. 6.2Chaining steps with and_then, transform and or_else
  26. 7Inside the Design and Implementation
  27. 7.1How the value is stored in memory
  28. 7.2When trivial behavior carries over
  29. 7.3Which types can go inside an optional
  30. 7.4Moving over from boost::optional and its roots
  31. 8Common Patterns and Examples in Practice
  32. 8.1Returning a value or nullopt on failure
  33. 8.2Using optional members and function parameters
  34. 8.3Workarounds for optional references and get
  35. 9Similar Types You Will Run Into
  36. 9.1Choosing between types with std::variant
  37. 9.2Other types like pairs, any and string_view
  38. 10References

Abstract

std::optional is a C++ type that holds either a value or no value, making absence explicit instead of relying on sentinel values, null pointers, or separate flags. Use it when a missing result or setting is a normal outcome, check whether it contains a value before reading it, and choose a fallback or error-handling approach that fits the situation. It stores the value inline without a heap allocation, helping make interfaces clearer while avoiding common mistakes such as unchecked access and confusing an empty optional with a false value.

Two wooden jewelry boxes on linen; one holds a gem, the other is empty as a hand hovers over it.
Figure 1 — Two wooden jewelry boxes on linen; one holds a gem, the other is empty as a hand hovers over it.

Think of a coat check at a busy restaurant. Sometimes you hand over a coat and get a ticket back, and sometimes there’s nothing to hand over at all. You’d rather not guess which one you’re holding.

std::optional is the C++ answer: a small wrapper that holds either a value of your chosen type or nothing, and the type itself says so.

In this post, we’ll walk through why it exists, how to create, check, and read one, and how to change and compose it. We’ll also date every feature to its standard, from C++17 onward, and flag the pitfalls working teams actually hit.

Why Std::optional Exists in the First Place

std::optional, added in C++17, holds either a value or nothing, so “no value” lives in the type itself. The std:: prefix marks names from the standard library’s namespace (std is short for standard).

The trouble with magic values and flags

  • nullptr ambiguity: a null pointer might mean “no value” or “failed,” and the pointer can’t say which.
  • Magic values: a -1 meaning “not found” works only if every caller remembers that.
  • Extra initialized-flag variables: a bool beside a value is two variables to keep in sync.
  • Hidden variable relationships: the compiler can’t see the flag-value link, which hurts optimization.

A parser developer stored find_token’s -1 in an unsigned variable, and it became a huge index.

Using unique_ptr and paying the heap cost

A common fix is std::unique_ptr, where null means “no value.” It works, but it says ownership when you only need maybe, and every value costs a heap allocation.

Consider a game engine giving each sprite an optional animation track: every one is another allocation and pointer to chase. std::optional stores the track inline, so “maybe” costs no heap at all.

When should you use std::optional?

We reach for it when no value is a normal outcome:

  • No-value as a natural state: a lookup that may find nothing, or a setting a user can leave unset.
  • Optional arguments: in build_display_name(first, middle, last), std::optionalstd::string says “no middle name” outright. An empty string can’t tell “not provided” from “left blank.”
  • boost::optional guidance: Boost users can apply the same advice, since the standard version arrived in C++17.
  • Nullable types: it’s the standard way to model a nullable value in plain C++, instead of a pointer or sentinel.

If absence is normal rather than exceptional, the signature should say so.

Creating and Initializing an Optional

Every std::optional starts one of a few ways, and each answers one question: does it hold a value yet? All of it arrived in C++17.

Starting with an empty optional

The default constructor gives you an empty optional, and std::nullopt says the same thing outright: std::optional<std::string> name = std::nullopt;. Neither initializes a contained value.

A game engine programmer can cache a player’s name as empty until a save file loads, with no sentinel string standing in for ‘not loaded yet.’ An empty optional is a missing value, not a zero value.

Creating from a value or converting types

The value constructor wraps a value you pass in: std::optional<int> retries{3};. Or let class template argument deduction (CTAD), a C++17 feature, pick the type: std::optional port{8080}; yields std::optional<int>.

Converting from an optional<U> works when T can be built from U, and an empty source stays empty. These converting constructors are conditionally explicit: they’re implicit only when U converts implicitly to T.

std::string won’t take a std::string_view implicitly, so converting an optional<std::string_view> to an optional<std::string> needs direct initialization, not =.

Constructing the value directly in place

Pass the std::in_place_t tag as std::in_place, and the arguments after it go straight to the contained T. The value is built in the optional rather than moved into it: no temporary, no extra move.

A firmware developer caching a separator line can write std::optional<std::string> rule{std::in_place, 40, '-'};. Braced lists reach a vector’s initializer_list constructor: std::optional<std::vector<int>> ids{std::in_place, {1, 2, 3}};.

The tag also separates arguments for T from an optional being copied. To rebuild the value later, use emplace: rule.emplace(40, '='); destroys the old value and constructs the new one in place.

How copying and moving an optional behaves

Copying an optional duplicates its value if it has one, and an empty one copies as empty. Either way, the copy constructor leaves the new object’s has_value() matching the source’s.

The move constructor transfers the value instead of copying it, and the source’s has_value() doesn’t change: it still holds a value, in a valid but unspecified state.

The move constructor is conditionally noexcept: it’s noexcept only when T’s move constructor is, and containers like std::vector rely on that when they reallocate. Keep T’s move noexcept when you can.

Technical illustration showing gem copying via flasks and a safe ramp handoff with vermilion and steel blue accents.
Figure 2 — Technical illustration showing gem copying via flasks and a safe ramp handoff with vermilion and steel blue accents.

Let make_optional deduce the type for you

std::make_optional deduces T from its argument, so auto retries = std::make_optional(3); gives you a std::optional<int>, just as class template argument deduction does with std::optional retries{3};.

You don’t need std::in_place here, because make_optional forwards its arguments to T’s constructor. It’s handy in containers.

After std::vector<std::optional<int>> scores;, a test-suite engineer can record a reported run with scores.push_back(std::make_optional(7)); and a silent one with scores.push_back(std::nullopt);. Nothing needs a sentinel score.

Checking Whether a Value Is Present

Before you read the value inside a std::optional, check that it’s actually there. Both forms below answer the same question, so pick the one that reads best in your codebase.

Checking with has_value or an if test

has_value() is the most explicit check. It returns true when the object holds a value and false when it’s empty, so a reviewer can see the condition without decoding anything. Use it when you want the code to say exactly what it means.

The shorter form relies on the explicit operator bool. An optional converts to bool, so it works directly as a condition. The conversion is explicit, though, so it only applies in a condition: an if, a loop, or an operand of ! or &&.

Assign it to a bool and the code won’t compile, so bool found = port; is an error. Write bool found = port.has_value(); instead.

Consider a backend developer who reads an optional request timeout from a config file. Without std::optional, that code often used -1 to mean “not set,” and every reader had to remember the special case. Now the test sits right where the fallback lives:

[Example 1:
std::optional<int> timeout_ms = read_timeout(config);
if (timeout_ms) {
    client.set_timeout(*timeout_ms);
} else {
    client.set_timeout(kDefaultTimeoutMs);
}

— end example]

The dereference on the next line only runs after the check passes, so the value is always there. The magic number is gone, and the default sits in the else branch where a reviewer will look for it. No sentinel to remember.

Reading the Value You Stored

Storing a value is only half the job. The read path decides what happens when the optional is empty, and we’ll walk through four options.

Checked reads with value that can throw

Calling value() is checked access: it returns a reference, or throws std::bad_optional_access if the optional is empty, so the failure surfaces at the line that caused it.

Reach for it when an empty optional means your logic is wrong, not that the data is missing. A game engine programmer loading a level’s spawn point is a good case: a missing one should stop the load, not drop the player into the void.

Using * and -> like a pointer

operator* and operator-> work like a pointer or smart pointer: *opt gives you the value, and opt->member reaches inside it. They skip the check, so the optional trusts you where value() checks for you.

If it’s empty, that’s undefined behavior (UB): the standard sets no requirements on what happens next.

Consider a firmware developer whose driver stores an optional calibration offset. The guard if (calibration_offset) before *calibration_offset keeps the read safe.

A refactor that drops the guard still compiles, but it can read an empty optional on first boot. A reviewer who spots the missing guard saves a bad release.

Falling back to a default with value_or

value_or gives you a fallback: opt.value_or(fallback) returns the contained value or the fallback, and it never throws std::bad_optional_access.

Because it returns by value, you get a copy, not a reference, so the call can’t change the stored object. For a large type, that copy costs time in a tight loop, so keep fallbacks cheap.

Think of a build engineer reviewing timeout_s.value_or(300). It reads cleanly, and the default sits right at the call site, with no separate if branch to maintain.

Looping over an optional with iterators

An optional has begin() and end(), so it works in a range-for loop. Its contiguous iterators point at adjacent elements in memory, and since it holds at most one value, the loop runs zero or one times.

Iterators on optional need C++26, so on C++17 or C++20 you’ll write a plain if instead. Iterators from an optional are invalidated when it’s initialized or destroyed. Don’t hold them across either event.

Changing, Assigning and Swapping an Optional

Once an optional holds a value, you’ll change it often, and nearly every rule comes down to one question: does it already hold one?

Assigning a value, nullopt or another optional

You can assign a value, std::nullopt, or another optional with =. An engaged optional (one holding a value) reuses its object, while an empty one constructs a new one:

Assigned from Target empty Target holds a value
opt = value constructs the value assigns into the value
opt = other constructs if other holds a value assigns if other holds a value, else destroys
opt = {} or opt = std::nullopt does nothing destroys the held value

Empty braces clear it too: opt = {}; matches opt = std::nullopt;. Moving avoids copies: opt = std::move(other); leaves other engaged but holding a moved-from object.

A game engine programmer with a std::optional<Texture> for a loading screen can use cache = std::move(loaded); to take over an asset without copying it.

Hands place, refine, and remove small figures from three glass cases on a workbench.
Figure 3 — Hands place, refine, and remove small figures from three glass cases on a workbench.

How to reset or emplace a std::optional?

To reset an optional, empty it with either of these:

  • reset() (C++17): destroys the held value, if any, and leaves the optional empty.
  • std::nullopt (C++17): opt = std::nullopt; has the same effect.

To build a value in place, use emplace (C++17). It destroys the held value first, then constructs the new one from your arguments, so no temporary is copied in, and it returns a reference to the new value.

If the constructor throws, the optional stays empty. The old value is already gone.

Swapping two optionals, empty or full

swap() exchanges two optionals whether they’re full or empty:

  • Both hold values: the values trade places.
  • One holds a value: the held value moves into the other optional, and the original ends up empty.
  • Neither holds a value: nothing happens.

swap is noexcept when the held type T’s move constructor and swap are both noexcept. T must also meet the Swappable requirement: std::swap or a swap found by argument-dependent lookup must be able to exchange it, or the call won’t compile.

Keeping the state safe when something throws

When an assignment throws, the optional’s engaged state doesn’t change, so has_value() returns what it returned before. Whether it still holds a value is one question.

What the value looks like afterward is another, and it depends on T’s guarantees: a type with the strong guarantee keeps its old value, while one with only the basic guarantee may be left in a valid but unspecified state, so don’t rely on its contents until you’ve reassigned it.

Comparing and Chaining Optional Values

Once you can build an optional, you’ll want to compare it and pass it through a few steps. The rules are simpler than they look.

How optionals stack up against values

Comparison works on optionals with a few rules:

  • Optional against optional. Two optionals compare by their contents when both hold a value.
  • Optional against a plain value. An optional holding 5 compares equal to 5.
  • Empty is less than any value. So it sorts first.
  • Two empties are equal. Two empty optionals compare equal.

Think of a game engine programmer sorting optional cooldown timers. The empty slots sort to the top, so one glance finds the ones with no timer.

Chaining steps with and_then, transform and or_else

According to a paper on monadic calculations, C++23 added monadic operations to std::optional: and_then, transform and or_else.

  • and_then calls a function that returns an optional, and skips it when the value is empty.
  • transform applies a function to the held value and wraps the result in an optional.
  • or_else supplies a fallback when the optional is empty.

Consider a firmware developer reading a temperature sensor that may not respond. transform converts raw counts to degrees, and_then rejects out-of-range readings, and or_else falls back to the last good one.

A failed read passes through untouched, with no nested if to unwind. Less nesting, same logic.

The three operations need C++23, so on C++17 or C++20 you’ll write explicit if checks instead.

Inside the Design and Implementation

Before you put an optional in a hot loop or a shared header, it helps to know what it stores.

How the value is stored in memory

An optional never touches the heap. It keeps a bool flag next to aligned storage, a block of raw memory, and the value sits inside a union. The flag says whether the union holds a live object. So an optional<int> is not a pointer to an int.

It’s the int itself with a flag beside it, and the overhead is about one extra byte.

Consider a game engine team with one optional<Transform> per entity in a flat array. Nothing lives on the heap, so there’s no allocator call per entity. No pointer to chase.

When trivial behavior carries over

When T has a trivial destructor, the optional’s destructor is trivial too, and nothing runs at scope exit. Copy, move and assignment carry over the same way.

Getting there takes a detour: Substitution Failure Is Not An Error (SFINAE) can switch an overload on or off, but it can’t enable or disable a destructor. So the library picks the right version through base class specializations.

A firmware developer who keeps an optional<std::uint16_t> in a register cache gets trivial copies, so copying the cache is as cheap as copying bare integers.

Which types can go inside an optional

Not every type qualifies. Here are the rules:

  • Lvalue references are allowed, but check which standard your compiler targets before you rely on this.
  • Complete non-array object types: the type must be fully defined and can’t be a raw array.
  • Not std::in_place_t or std::nullopt_t: the tag types used for in-place construction and empty optionals can’t be wrapped.
  • Cpp17Destructible: the type must meet the C++17 named requirement of that name, so it can be destroyed.

A parser team that needs a fixed-size buffer should wrap std::array, not a raw array: optional<int[4]> is rejected, but optional<std::array<int, 4>> works.

Clerk places a stamped wooden crate into a glass case while refusing tiles marked with red Xs.
Figure 4 — Clerk places a stamped wooden crate into a glass case while refusing tiles marked with red Xs.

Moving over from boost::optional and its roots

The standard std::optional grew out of boost::optional, so if you already use the Boost version, you know most of the interface. For many teams the migration is easy because the names and behavior are familiar.

A gameplay team whose Boost dependency exists only for optional can drop it once the codebase is on C++17. If you’ve used boost::optional, you’re closer to the standard than you think.

Common Patterns and Examples in Practice

Most std::optional code takes one of three shapes: a return value, a member or parameter, or a reference. Here’s how each looks, and where teams trip.

Returning a value or nullopt on failure

A firmware developer parsing a port number can wrap std::from_chars (C++17) in a function that returns std::optional<int>. Bad input returns nullopt, so the failure travels in the return type instead of an error code a caller might skip.

Factory-like functions work the same way. A load_config(path) returning std::optional<Config> treats a missing file as an ordinary outcome.

Watch value_or: its argument is always evaluated, so value_or(read_defaults_from_disk()) hits the disk even when a value exists. Likewise, if (!flag) on an std::optional<bool> tests for absence, not false; write flag == false instead.

Use std::optional when absence is the whole story. When the caller needs to know why, std::expected (C++23) holds a value or an error. A std::variant (C++17) can hold either too, but it doesn’t say which alternative is the error.

Using optional members and function parameters

A Contact with a std::optional<std::string> middle_name says plainly that not everyone has one. Parameters work the same way: a std::optional<std::string_view> title lets callers pass std::nullopt rather than a magic empty string. Nobody has to guess.

Moving from an optional moves the value inside but doesn’t empty the optional, so call reset() when you mean absent. Copying an optional copies what it holds, so take a large read-only std::optional<T> by const&.

Workarounds for optional references and get

The standard doesn’t allow std::optional<Widget&>, so use std::optional<std::reference_wrapper<Widget>> from <functional>. A desktop team’s window registry returns that type, so the caller draws only when the lookup succeeds, and no window is copied.

Inside an if (auto w = find_window(id)), call w->get().draw(), where get() returns the Widget&.

Similar Types You Will Run Into

Several standard types look like std::optional, but each answers a different question.

Choosing between types with std::variant

When a value can be one of several types, std::variant (C++17) is the tool.

It’s union-like storage that records which alternative is active, so you don’t track that by hand. std::variant answers which type you hold, while std::optional answers whether you hold anything.

std::get returns the alternative you name, or throws std::bad_variant_access on a mismatch. std::get_if returns a pointer, or nullptr, for a quick check.

std::visit (C++17) calls the branch matching the active type. Pass it an overload pattern, a struct that inherits several lambdas, since the standard library doesn’t provide one. Consider a firmware developer decoding sensor frames.

When a new frame type ships without a handler, the build fails instead of a frame slipping through unnoticed.

A valueless_by_exception variant holds no alternative if constructing a new one throws, and std::visit throws on it. Check index() == std::variant_npos when your types can throw.

std::monostate (C++17) is an empty placeholder for an idle state. List it first, as in std::variant<std::monostate, Connected, Failed>, and the variant becomes default-constructible.

Other types like pairs, any and string_view

std::pair (C++98) and std::tuple (C++11) bundle values without a named struct, which suits a short-lived return value.

std::any (C++17) holds a value of any copyable type.

Where std::variant’s types are closed and fixed at compile time, std::any is open. std::any_cast retrieves the value and throws std::bad_any_cast on a mismatch, so reach for std::any only when the types can’t be known ahead of time.

std::string_view (C++17) is a non-owning view of characters, so passing one copies nothing. The sv suffix (in std::string_view_literals, C++17) builds one from a literal, as in “config”sv.

Lifetime is the catch: the view can’t outlive the string it points into.

Once you see std::optional as a plain statement that a value may be absent, old sentinel values and out-parameter workarounds start to look like guesswork.

Check which standard your project builds with, use it where a missing value is a normal outcome, and keep the pitfalls in mind during code review.

A missing value deserves a type of its own, and since C++17 you have one.

References

  1. Application of Monadic Calculations in Solving Numerical Problems — doi.org (2024)

Questions

What is std :: in cpp?

`std::` is the namespace prefix for names in the C++ standard library. For example, `std::optional` and `std::string` are standard-library types.

How to reset a std :: optional?

Call `opt.reset()` or assign `std::nullopt`, as in `opt = std::nullopt;`. Both destroy any contained value and leave the optional empty.

What does std :: optional mean?

`std::optional<T>` is a C++17 wrapper that holds either a value of type `T` or no value. It represents absence directly in the type, without needing a sentinel value.

Should I use std :: endl or \n?

Use `\n` for a newline in most cases. `std::endl` also flushes the output stream, which can add unnecessary overhead; use it when you specifically need to flush immediately.

When to use std :: optional?

Use `std::optional` when a value may naturally be absent, such as a lookup result, an unset setting, or an optional function argument. If absence is an ordinary outcome, it can express that in the type; if callers need to know why an operation failed, consider an error-bearing type such as `std::expected`.

Read next

  1. volatile keyword in C++: what it does and does not doLanguage · Miriam Castellanos · written for C++17
  2. C++ move semantics: what std::move and && really doLanguage · Miriam Castellanos · written for C++20
  3. std::visit Explained: Calling Handlers for Variant TypesLanguage · Miriam Castellanos