skip to content

In C++26, what does std::optional<T&> do on assignment and on construction from a temporary, and why was it ill-formed before?

level: seniorimportance: nice to knowfreq 18%

answer

  1. a pointer under the hood
  2. rebind, not assign-through
  3. temporaries are refused
  4. a static_assert in older modes

basics

~20 s

C++26 adds a partial specialization std::optional<T&> that stores a pointer: assignment rebinds it to another object instead of writing through, and construction from a temporary is deleted. Before C++26 a reference was not a valid contained type.

solid answer

~40 s

Up to C++23, `optional<T>` required `T` to be a destructible object type, so `std::optional<int&>` was ill-formed; libc++ rejects it with a `static_assert` saying an optional of a reference type is ill-formed. Code used `T*` or `optional<std::reference_wrapper<T>>` instead. C++26 adds the partial specialization `optional<T&>`, specified as holding a `T*` and trivially copyable. Its copy assignment is defaulted, so `r = other;` **rebinds** `r` to `other` and never writes into the object it referred to; to change that object you write `*r = value`. Constructors that would bind the reference to a temporary are deleted, so `std::optional<const std::string&> s = std::string("x");` does not compile. `value_or` returns `remove_cv_t<T>` by value, and `*r` returns `T&`.

code

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

using Config = std::map<std::string, std::string>;

// C++26: return a reference to the stored entry, or nothing, without copying
std::optional<std::string&> find_entry(Config& cfg, const std::string& key) {
    if (auto it = cfg.find(key); it != cfg.end()) return it->second;
    return std::nullopt;
}

int main() {
    Config cfg{{"host", "db.internal"}, {"mode", "ro"}};
    if (auto host = find_entry(cfg, "host")) *host = "db.replica";  // writes into the map
    std::cout << cfg["host"] << '\n';

    std::string local = "local";
    std::optional<std::string&> r = find_entry(cfg, "mode");
    r = local;                       // rebinds r to local; cfg["mode"] is untouched
    std::cout << cfg["mode"] << ' ' << *r << '\n';
    std::cout << find_entry(cfg, "port").value_or("5432") << '\n';
}

go deeper

for a junior

Know that optional of a reference did not compile before C++26 and that C++26 adds it. Earlier code used a pointer or reference_wrapper.

for a middle

Explain rebinding assignment versus assign-through, why construction from a temporary is deleted, and why value_or returns by value.

for a senior

Judge where optional<T&> is safe: references into stable storage only, the lifetime still being the caller's problem, and toolchain support being partial in 2026.

for a principal

Decide when a codebase may adopt C++26 vocabulary types, given mixed compiler support and the need for a pre-C++26 spelling in public headers.

## The gap before C++26 A lookup that wants to hand back **the stored entry itself**, not a copy, had no clean vocabulary type. `std::optional<std::string&>` was not allowed: through C++23 the draft required the contained type to meet the *Cpp17Destructible* requirements, which a reference type does not, and the contained value is an object allocated within the optional's storage. Implementations enforce it. With Apple clang and libc++ under `-std=c++23`, the declaration fails with: `static assertion failed due to requirement '!is_reference_v<int &>': instantiation of optional with a reference type is ill-formed` Workarounds were a raw pointer (whose nullness says "absent", covered with pointers), or `std::optional<std::reference_wrapper<T>>`, which works but reads awkwardly (`opt->get()`). ## What C++26 specifies C++26 adds `template<class T> class optional<T&>` as a partial specialization. Its key properties, from the draft: - **Representation.** The exposition-only member is `T* val = nullptr;`, and the object contains a value if and only if `val != nullptr`. Each `optional<T&>` is a **trivially copyable** class. - **Access.** `operator*` returns `T&` and `operator->` returns `T*`; `value()` returns `T&` and throws `std::bad_optional_access` when empty. - **`value_or`** returns `remove_cv_t<T>` **by value**, because a fallback reference could dangle. - **Monadic operations.** `and_then`, `transform` and `or_else` exist; `transform(f)` returns `optional<invoke_result_t<F, T&>>`. - **Ranges.** `ranges::enable_borrowed_range<optional<T&>>` is `true`, since the optional does not own what it refers to. ## Assignment rebinds The specialization declares only these assignments: `operator=(nullopt_t)`, a defaulted copy assignment, and `emplace(u)`. There is no "assign through" operator. So: 1. `r = local;` converts `local` into a temporary `optional<std::string&>` through the converting constructor, then copy-assigns it: `r` now refers to `local`. 2. The string `r` referred to before is **unchanged**. 3. `*r = "new";` writes into whichever object `r` currently refers to. This matches what a pointer would do and avoids the trap where assignment means "rebind" when empty but "write through" when engaged. In a run with clang 21 and `-std=c++2c`, a map entry `"ro"` stayed `"ro"` after `r = local;`, and `*r` read `local`. ## Temporaries are refused The constructor `optional(U&& u)` is **defined as deleted** when `reference_constructs_from_temporary_v<T&, U>` is `true`, and the `in_place_t` constructor is constrained the same way. So the classic dangling bug does not compile: ```cpp // C++26: error, the converting constructor is deleted std::optional<const std::string&> s = std::string("tmp"); ``` Clang reported that the conversion `invokes a deleted function`. A `const T&` function parameter accepts temporaries; `optional<const T&>` deliberately does not. ## Against the old workarounds - **`T*`** says "maybe absent" only by convention. It also allows arithmetic, `delete` and conversion to `bool` in ways that blur ownership, and nothing in the type says the pointer is non-owning. - **`std::optional<std::reference_wrapper<T>>`** works since C++17 and also rebinds on assignment, but every read is `opt->get()` and `value_or` needs a `reference_wrapper` fallback. - **`std::optional<T&>`** reads like any other optional (`*r`, `r->size()`, `if (r)`), states non-ownership in its type, and is trivially copyable, so it is as cheap to pass as a pointer. ## Practical guidance | Need | Type | |---|---| | maybe a copy of the value | `std::optional<T>` | | maybe a reference into existing storage, C++26 | `std::optional<T&>` | | same, before C++26 | `T*` or `std::optional<std::reference_wrapper<T>>` | - The referred-to object must outlive the optional; the type stops temporaries, not a container that reallocates or erases the entry. - Support is new and partial across toolchains. Apple clang 21 with libc++ accepted the code under `-std=c++2c`; check the feature-test macro `__cpp_lib_optional` (202506L in the C++26 draft) before relying on it in portable code.

  • Why does optional<T&>::value_or return a value rather than a T&?
    The fallback is usually a temporary or a literal, and returning a reference to it would dangle as soon as the full expression ends. The C++26 draft therefore declares `value_or` as returning `remove_cv_t<T>` by value: you get a copy of the referred-to object or of the fallback, never a reference to either.
  • Does optional<T&> protect against the referred-to map entry being erased?
    No. It refuses only construction that would bind to a temporary, through `reference_constructs_from_temporary_v`. If the map entry is erased or a vector reallocates, the stored pointer dangles exactly like a raw `T*` would, and dereferencing it is undefined behaviour.

  • Assigning to an engaged optional<T&> writes through to the referred object
  • std::optional<int&> has always worked since C++17
  • optional<const T&> extends a temporary's lifetime like a const T& parameter
  • optional<T&> owns a copy of the object it refers to

Assumes the C++26 draft (N5050), which adds the optional<T&> partial specialization; through C++23 an optional of a reference type is ill-formed.