In C++23, how does a function returning std::expected<T, E> report a failure, and how does the caller read the error?
answer
- a value or a reason
- a wrapper type for the bad case
- no implicit conversion from E
- the exception carries the error
basics
~10 sIt returns std::unexpected(err), which constructs the expected in its error state; a plain T converts to the success state. The caller tests has_value() or if (r), reads *r or r.error(), and value() throws std::bad_expected_access<E>.
solid answer
~40 s`std::expected<T, E>` (C++23, header `<expected>`) holds either a `T` or an `E` inside itself. Success is easy: `return port;` converts a `T` implicitly. Failure must be spelled out: `return std::unexpected(std::errc::invalid_argument);`, or construct in place with the `std::unexpect` tag. A bare `E` does not convert, which keeps `expected<int, int>` unambiguous. The caller checks `has_value()` or `if (r)`, then reads `*r` for the value or `r.error()` for the reason; both accessors are unchecked, so reading the wrong one is undefined behaviour. `r.value()` is the checked path: on an error it throws `std::bad_expected_access<E>`, whose `error()` hands back a copy of the stored error. `value_or` and `error_or` give fallbacks, and `std::expected<void, E>` covers operations with nothing to return.
code
cpp · 27 lines#include <charconv>
#include <expected>
#include <iostream>
#include <string>
#include <system_error>
std::expected<int, std::errc> parse_port(const std::string& s) {
int v = 0;
auto [p, ec] = std::from_chars(s.data(), s.data() + s.size(), v);
if (ec != std::errc{}) return std::unexpected(ec);
if (p != s.data() + s.size()) return std::unexpected(std::errc::invalid_argument);
return v;
}
int main() {
auto ok = parse_port("8080");
auto bad = parse_port("80x");
std::cout << ok.has_value() << ' ' << *ok << '\n';
std::cout << bad.has_value() << ' '
<< (bad.error() == std::errc::invalid_argument) << '\n';
std::cout << bad.value_or(5432) << '\n';
try { (void)bad.value(); }
catch (const std::bad_expected_access<std::errc>& e) {
std::cout << "caught, error()==invalid_argument: "
<< (e.error() == std::errc::invalid_argument) << '\n';
}
}go deeper
Know that std::expected is C++23, holds a value or an error, and that failure is returned with std::unexpected(err). Read it with has_value(), *r and r.error().
Explain why a bare E does not convert, what value() throws and what it carries, and that *r and error() are unchecked accessors.
Discuss error type design: a cheap copyable E for value(), expected<void, E> for operations without results, and [[nodiscard]] since ignoring a result compiles silently.
Consider the minimum standard a library can require: std::expected needs C++23 consumers, and that decision shapes whether the API can use it at all.
## What std::expected adds over std::optional `std::optional<T>` answers "is there a value?". `std::expected<T, E>` (C++23, header `<expected>`) answers "is there a value, and if not, **why**?". It contains either a value of type `T` or an error of type `E`, nested within the object, with a flag saying which. In the config-loader scenario, a lookup that may find nothing fits `optional`, while a parser that may fail with a reason fits `expected<int, std::errc>`. ## Producing a result - **Success**: `return v;` — a `T` converts implicitly into the value state. - **Failure**: `return std::unexpected(ec);` — `std::unexpected<E>` is a small wrapper class template with a deduction guide, so `std::unexpected(ec)` deduces `E`. - **In-place failure**: `std::expected<T, E>(std::unexpect, args...)` constructs the error directly, useful when `E` is not cheaply movable. - **No value at all**: `std::expected<void, E>` represents "succeeded" or "failed with E". A bare `E` **does not** convert. Returning `std::errc::invalid_argument` from a function declared to return `std::expected<int, std::errc>` fails to compile; clang reported `no viable conversion from returned value of type 'std::errc' to function return type 'std::expected<int, std::errc>'`. That rule is deliberate: with `expected<int, int>`, `return 5;` must mean success, and failure must be marked. The draft also limits the types: `T` must be `void` or a complete non-array object type, and `E` must be a valid argument for `unexpected` (a non-array, non-cv-qualified object type that is not itself an `unexpected`). Reference types are out for both. ## Reading a result | Member | Value state | Error state | |---|---|---| | `has_value()`, `if (r)` | `true` | `false` | | `*r`, `r->m` | the value | precondition violated: undefined behaviour | | `r.error()` | precondition violated: undefined behaviour | the error | | `r.value()` | the value | throws `std::bad_expected_access<E>` | | `r.value_or(x)` | the value | `x` converted to `T` | | `r.error_or(e)` | `e` converted to `E` | the error | Key details: 1. `value()` **mandates** that `E` is copy constructible, because the exception it throws, `bad_expected_access<E>`, stores a copy of the error. The handler reads it back with `e.error()`. 2. `std::bad_expected_access<E>` derives from `std::bad_expected_access<void>`, which derives from `std::exception`, so one handler can catch every instantiation. 3. `operator*` and `error()` are unchecked and `noexcept`. In C++26 their preconditions become **hardened preconditions**, like `optional`'s. ## Comparing and changing state `std::expected` supports `==` against another `expected`, against a plain value and against an `unexpected`: - `r == 8080` is `true` only when `r` holds a value equal to 8080; an error state compares unequal. - `r == std::unexpected(std::errc::invalid_argument)` is `true` only when `r` holds that error. - Assigning `r = 9090;` or `r = std::unexpected(e);` switches state; `r.emplace(args...)` constructs a new value in place. There is no empty state: unlike `optional`, an `expected<T, E>` always holds exactly one of the two, so there is no `reset()` and no default "nothing" to fall back to. A default-constructed `expected<T, E>` holds a value-initialized `T`. ## Typical interview probes - *Why `std::unexpected` and not just `E`?* Because `T` and `E` may be the same or interconvertible type, and the reader of `return x;` must never have to guess which state it makes. - *What does `value()` throw?* Not `std::bad_optional_access`, and not the error itself: `std::bad_expected_access<E>`, carrying the error. - *Does `expected` allocate?* No. Like `optional`, the active member lives inside the object; its size is roughly the larger of `T` and `E` plus a flag, the exact layout being the implementation's choice. - *Can I ignore a returned `expected`?* The standard does not require a warning; with Apple clang and libc++, discarding one compiled silently under `-Wall -Wextra`. Mark the functions that return it `[[nodiscard]]` if you want the compiler to complain. ## A note on the name `std::unexpected` once also named a C++98 function tied to dynamic exception specifications; that function was removed in C++17, and since C++23 the name belongs to this class template.
- Why does std::expected<int, std::errc>::value() require std::errc to be copy constructible?Because on the error path `value()` throws `std::bad_expected_access<E>` built from the stored error, and the exception object must be copyable. The draft states it as a Mandates clause on every `value()` overload, so with a move-only `E` any call to `value()` is ill-formed, even on a path that never sees an error. Check `has_value()` and read `*r` or `error()` instead.
- When would you choose std::expected<void, E> over returning bool or an error code?For an operation that produces nothing but can fail with a reason, such as saving a file. `expected<void, E>` keeps the same reading pattern as every other `expected` (check, then `error()`), composes with `and_then` and `transform_error`, and makes the success case a distinct state rather than a magic error value such as zero.
- You can return the error value directly and it converts to the error state
- value() on an error throws the stored error object itself
- std::expected stores the error on the heap to keep the object small
- error() throws if the expected actually holds a value
- std::expected has been in the standard library since C++17
Assumes C++23, which added std::expected, std::unexpected and std::bad_expected_access in <expected>; C++20 and earlier have none of them.