In C++, what happens when code calls value() versus operator* on an empty std::optional, and which belongs in production code?
answer
- one checks, one assumes
- an exception type named after the class
- a precondition nobody tests
- hardened library builds
basics
~20 svalue() checks and throws std::bad_optional_access when the optional is empty; operator* and operator-> carry an unchecked precondition, so dereferencing an empty optional is undefined behaviour in C++23. Check first and dereference, or use value() or value_or.
solid answer
~40 s`value()` is the checked accessor: the standard specifies it as `has_value() ? val : throw bad_optional_access()`, so an empty optional raises `std::bad_optional_access`, which derives from `std::exception`. `operator*` and `operator->` are `noexcept` and carry a precondition that the optional holds a value; in C++23 breaking it is undefined behaviour, so you may read garbage, crash, or watch the optimizer delete your error handling. C++26 turns that precondition into a **hardened precondition**: a hardened implementation must stop the program, while a non-hardened one is still undefined. Library modes already do this today, for example libc++'s `_LIBCPP_HARDENING_MODE` and libstdc++'s `_GLIBCXX_ASSERTIONS`. In production I dereference only right after a check (`if (opt) use(*opt);`), use `value_or` for defaults, and keep `value()` for the case where emptiness is a genuine error that an exception should report.
code
cpp · 24 lines#include <iostream>
#include <map>
#include <optional>
#include <string>
std::optional<int> find_timeout(const std::map<std::string, int>& cfg) {
if (auto it = cfg.find("timeout_ms"); it != cfg.end()) return it->second;
return std::nullopt;
}
int main() {
const std::map<std::string, int> cfg{{"retries", 3}};
std::optional<int> t = find_timeout(cfg);
if (t) std::cout << "checked deref: " << *t << '\n'; // operator* only after a check
std::cout << "fallback: " << t.value_or(1000) << '\n';
try {
std::cout << t.value() << '\n'; // checked access
} catch (const std::bad_optional_access& e) {
std::cout << "value() threw std::bad_optional_access\n";
}
// std::cout << *t; // empty: undefined behaviour in C++23
}go deeper
Remember the split: value() throws std::bad_optional_access on an empty optional, while *opt is not required to check anything. Always test the optional before dereferencing it.
Explain why operator* is noexcept and unchecked, what undefined behaviour means for the program, and how value_or fits in. Mention that std::bad_optional_access derives from std::exception.
Talk about catching the bug class in practice: hardened library modes in test builds, the C++26 hardened precondition, and code review rules for bare dereferences.
Weigh the cost of checks against safety for a codebase: enabling a hardened standard library in production, its runtime cost, and which accessor style the team standardises on.
## Two ways to get the value out `std::optional<T>` offers checked and unchecked access to its contained value, and interviewers use the pair to see whether a candidate knows where the checks actually are. | Accessor | Declared | Empty optional (C++23) | |---|---|---| | `value()` | not `noexcept` | throws `std::bad_optional_access` | | `operator*()` | `noexcept` | precondition violated: **undefined behaviour** | | `operator->()` | `noexcept` | precondition violated: **undefined behaviour** | | `value_or(x)` | not `noexcept` | returns `x` converted to `T` | The draft specifies `value()` as equivalent to `return has_value() ? val : throw bad_optional_access();`. `std::bad_optional_access` derives from `std::exception`, and its `what()` string is implementation-defined. ## Why operator* does not check `operator*` exists for the common case where the caller has just checked: `if (auto t = find_timeout(cfg)) wait(*t);`. Checking again inside would cost a branch on every access, so the standard makes the check the caller's job by stating a precondition ("`has_value()` is `true`") instead of an effect. Breaking a library precondition is undefined behaviour, which means: - the read may return whatever bytes sit in the unused storage, for example a stale value from an earlier `reset()`; - a crash is possible but **not guaranteed**, so tests can pass; - the optimizer may assume the optional was engaged and remove a later `has_value()` test on the same path. The output of such a program is never "the default value of `T`". No accessor default-constructs a `T` for you. ## What C++26 changes C++26 rewrites the precondition of `operator*`, `operator->` and several other observers as a **hardened precondition**. The library introduction defines what that means: 1. In a **hardened implementation**, the condition is checked as a contract assertion with a terminating semantic before anything else happens, so the program stops. 2. In a **non-hardened implementation**, violating it is still undefined behaviour. Whether a build is hardened is an implementation's choice of mode. Both major standard libraries already ship such modes for older standards: libc++ checks `operator*` with `_LIBCPP_ASSERT_VALID_ELEMENT_ACCESS` when `_LIBCPP_HARDENING_MODE` selects a hardened mode (on Apple clang, a `-D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST` build of an empty-dereference program stopped with a trap), and libstdc++ guards it with `__glibcxx_assert`, active under `_GLIBCXX_ASSERTIONS`. ## Moving out leaves it engaged The rvalue overloads matter for performance and for one surprise. `*std::move(opt)` and `std::move(opt).value()` return `T&&`, so `std::string s = *std::move(opt);` moves the string out instead of copying it. The optional itself, however, **still contains a value**: a moved-from `std::string` in a valid but unspecified state. The draft says the same for moving the whole optional: after `auto b = std::move(a);`, `a.has_value()` is unchanged. On a Mac run, both checks printed `1`. Code that moves a value out and then tests `has_value()` to mean "not consumed yet" is therefore wrong; call `reset()` after moving if emptiness should mean consumed. ## Choosing an accessor in production code - **Check, then dereference** for normal control flow. The check is explicit, the dereference is free. - **`value_or(fallback)`** when a default exists. Remember that its argument is evaluated even when the optional is engaged. - **`value()`** when an empty optional means a broken assumption that an exception should carry up the stack, for example a required config key in a startup path that already reports failures by exception. - **Never `*opt` "because it is always set"** without a check or an assertion nearby; the next refactor makes it sometimes-unset, and nothing tells you. A senior answer also mentions what *not* to do: wrapping every `*opt` in `try`/`catch` does nothing, because `operator*` never throws. Only `value()` throws, and catching `std::bad_optional_access` around ordinary control flow is usually a sign the code should have tested `has_value()` instead.
- A colleague wraps *opt in try/catch for std::bad_optional_access. What is wrong with that?`operator*` is declared `noexcept` and never throws; on an empty optional it simply has undefined behaviour in C++23. Only `value()` throws `std::bad_optional_access`. The handler is dead code that gives false confidence. Either test `has_value()` before dereferencing, or call `value()` if an exception is really the reporting mechanism wanted.
- How can a team catch empty-optional dereferences in testing without changing the code?Build tests with the standard library's hardening or assertion mode: libc++ checks `operator*` when `_LIBCPP_HARDENING_MODE` is set, and libstdc++ checks it under `_GLIBCXX_ASSERTIONS`. An empty dereference then stops the program at the faulty line instead of reading garbage. C++26 standardises the idea as hardened preconditions.
- Dereferencing an empty optional returns a default-constructed value
- operator* throws std::bad_optional_access just like value()
- Undefined behaviour here always crashes, so tests would catch it
- value() and operator* compile to the same code, so the choice is style
- Wrapping *opt in try/catch makes the dereference safe
Assumes C++23, where operator* on an empty optional is undefined behaviour; C++26 makes it a hardened precondition that a hardened implementation must stop on.