skip to content

In C++17, how should a config lookup function return a value that may be missing, and how does the caller read it?

level: juniorimportance: must knowfreq 68%

answer

  1. a wrapper that may be empty
  2. the empty state has its own constant
  3. test it like a bool
  4. a fallback supplied at the call site

basics

~10 s

Return std::optional<T>: return the found value, or std::nullopt when the key is missing. The caller tests it with has_value() or if (opt), reads it with *opt, or takes a default with value_or(fallback).

solid answer

~40 s

I would declare the lookup as returning `std::optional<std::string>` (C++17, header `<optional>`). When the key exists I return the value, which converts implicitly; when it does not I `return std::nullopt;` (or `return {};`). The caller then writes `if (auto host = lookup(cfg, "host")) use(*host);` because `optional` converts explicitly to `bool` in a condition, or calls `has_value()`. When there is a sensible default, `lookup(cfg, "port").value_or("5432")` gives the value or the fallback in one expression. The contained value lives inside the `optional` object itself; the standard forbids extra storage such as a heap allocation, so returning an `optional<int>` costs an `int` plus a flag, not a `new`. Unlike a sentinel such as `-1` or an empty string, the empty state cannot be mistaken for a real value.

code

cpp · 21 lines
cpp
#include <iostream>
#include <map>
#include <optional>
#include <string>

std::optional<std::string> lookup(const std::map<std::string, std::string>& cfg,
                                  const std::string& key) {
    if (auto it = cfg.find(key); it != cfg.end()) return it->second;
    return std::nullopt;
}

int main() {
    const std::map<std::string, std::string> cfg{{"host", "db.internal"}};
    if (auto host = lookup(cfg, "host")) std::cout << "host=" << *host << '\n';
    std::cout << "port=" << lookup(cfg, "port").value_or("5432") << '\n';
    auto user = lookup(cfg, "user");
    std::cout << std::boolalpha << user.has_value() << '\n';
    try { std::cout << user.value() << '\n'; }
    catch (const std::bad_optional_access& e) { std::cout << "caught bad_optional_access\n"; }
    std::cout << sizeof(std::optional<int>) << ' ' << sizeof(int) << '\n';
}

go deeper

for a junior

Know the three moves cold: return std::nullopt for missing, test with if (opt) or has_value(), and read with *opt or value_or(default). Say that it lives in <optional> since C++17.

for a middle

Explain that the value sits inside the optional with no heap allocation, why value_or always evaluates its argument, and why optional<bool> in a condition tests presence rather than truth.

for a senior

Show judgment about API shape: when a sentinel is acceptable, when optional documents absence better, and when the caller needs to know why nothing came back, which points to std::expected instead.

for a principal

Frame optional as part of a library's vocabulary: consistent use across interfaces, no mixing of sentinels and optionals for the same concept, and a clear rule for when absence is normal rather than an error.

## What std::optional is `std::optional<T>` (C++17, header `<optional>`) is a class template that, at any moment, either **contains a value** of type `T` or contains nothing. It is the standard library's vocabulary type for "a value that may be absent": a lookup that may find nothing, a field that may be unset, a parse that may produce no number. The standard's wording on storage matters for performance-minded code: when an `optional<T>` contains a value, that value is **nested within the optional object itself**, and implementations are not permitted to use additional storage such as dynamic memory. So `optional<int>` is an `int` plus an "engaged" flag, laid out in place. Its exact `sizeof` is the implementation's choice; with Apple clang and libc++ on a 64-bit Mac, `sizeof(std::optional<int>)` printed 8. ## Producing an optional from a function For a config loader, the lookup returns `std::optional<std::string>`: - `return it->second;` — a `std::string` converts implicitly into an engaged `optional`. - `return std::nullopt;` — `std::nullopt` is a constant of type `std::nullopt_t` that means "empty". - `return {};` — a value-initialized `optional` is also empty; `nullopt` reads more clearly. The return type is the documentation: a caller cannot forget that the key may be missing, because it holds an `optional`, not a `std::string`. ## Building and changing one in place Returning a value is the common case, but `optional` can also be filled and emptied without a temporary: - `std::make_optional<Config>(path, mode)` and the constructor `std::optional<Config>(std::in_place, path, mode)` build the contained object directly from constructor arguments. - `opt.emplace(args...)` destroys any current value and constructs a new one in place, returning a reference to it. - `opt.reset()` or `opt = std::nullopt;` destroys the contained value and leaves the optional empty. Because the value lives inside the optional, its destructor runs when the optional is reset, reassigned to empty or destroyed, exactly like a member variable's. ## Reading it on the caller's side | Operation | Empty optional | Engaged optional | |---|---|---| | `has_value()` / `if (opt)` | `false` | `true` | | `*opt`, `opt->size()` | precondition violated: undefined behaviour | the value | | `opt.value()` | throws `std::bad_optional_access` | the value | | `opt.value_or(x)` | `x` converted to `T` | a copy of the value | The everyday pattern is a check followed by a dereference: 1. Bind it in the condition: `if (auto host = lookup(cfg, "host")) connect(*host);` 2. Or ask for a default: `int port = lookup_int(cfg, "port").value_or(5432);` 3. Or call `value()` when an empty result really is exceptional and an exception is acceptable. ## Pitfalls interviewers like - **`value_or` evaluates its argument first.** It is an ordinary function argument, so `opt.value_or(expensive_default())` runs `expensive_default()` even when `opt` is engaged. If the fallback is costly, write `opt ? *opt : expensive_default()` instead. - **`std::optional<bool>` in a condition** tests whether a value is present, not what it is: `if (verbose)` is `true` for an engaged `false`. Write `verbose.value_or(false)` or `verbose == true`. - **`value_or` returns `T` by value**, so `optional<std::string>::value_or` copies the string out; read through `*opt` when you only need a look. - **Comparisons are defined**: `opt == 5` is `false` for an empty `opt`, and an empty optional compares less than any engaged one. That is convenient, and it also lets a missing value slip through a comparison silently. ## Why not a sentinel value Before C++17, code often returned `-1`, an empty string, or a `bool` with an output parameter. A sentinel steals a value from the domain (an empty string may be a legitimate config value), and an output parameter forces the caller to declare an object before it knows whether one exists. `std::optional` keeps the "missing" state separate from every real value of `T` and lets the caller decide, at the call site, between checking, defaulting and throwing. Error *details* are a different need: `optional` says only that nothing is there, not why. When the caller must know whether the key was missing or the text failed to parse, the C++23 `std::expected<T, E>` carries the reason.

  • Why does opt.value_or(load_default()) sometimes show up in a profile even when opt is always engaged?
    Because `value_or` is an ordinary member function and its argument is evaluated before the call. `load_default()` runs every time, whether or not the optional holds a value, and only then does `value_or` decide which one to return. When the fallback is expensive, write `opt ? *opt : load_default()`, which calls it only on the empty path.
  • Does returning std::optional<std::vector<int>> allocate memory for the optional itself?
    No. The standard requires the contained value to be nested within the optional object and forbids additional storage such as dynamic memory for it. The vector inside may allocate its own elements as usual, but the optional adds only an engaged flag beside the vector; there is no separate heap block for the wrapper.

A parcel locker slot: it either holds your parcel or is empty, the display tells you which before you open it, and nobody has to put a fake parcel in the slot to mean nothing arrived.

  • std::optional stores its value on the heap like a smart pointer
  • Returning -1 or an empty string is just as clear as an optional
  • if (opt) on an optional<bool> checks whether the flag is true
  • value_or only evaluates its fallback when the optional is empty
  • An empty optional dereferenced with * returns a default-constructed T