skip to content

A C++ dialog returns a button handler built with [&]; why does a later click misbehave, and how do init captures fix it?

level: middleimportance: must knowfreq 70%

answer

  1. the dialog's locals die at return
  2. references do not extend lifetime
  3. undefined behaviour, not a stale value
  4. name = expression inside the brackets
  5. std::move a unique_ptr into the closure

basics

~20 s

[&] stores references to the function's locals, which are destroyed when it returns, so calling the handler later is undefined behaviour. Capture by copy instead, or use an init capture such as [d = std::move(draft)] so the closure owns the state.

solid answer

~40 s

A by-reference capture does not extend the lifetime of what it refers to. When the dialog function returns, its locals are destroyed, and the handler's references to them dangle; invoking it is undefined behaviour, which may print garbage, crash, or appear to work. Clang 21 warned about the direct `return [&] { ... }` case with `-Wreturn-stack-address`, but it cannot see every path a handler takes, and AddressSanitizer reports `stack-use-after-return` when that check is enabled. The fix is to make the closure **own** its state: capture cheap values by copy, and use a C++14 **init capture**, `[name = expression]`, to move expensive or move-only state in, for example `[d = std::move(draft)]` for a `std::unique_ptr`. An init capture declares a new closure member initialized when the lambda is created.

code

cpp · 12 lines
cpp
#include <cstdio>
#include <string>

auto make_save_handler() {
  std::string title = "Report";
  return [&] { std::printf("saving %s\n", title.c_str()); };  // dangles
}

int main() {
  auto on_save = make_save_handler();
  on_save();  // undefined behaviour: title was destroyed on return
}

go deeper

for a junior

Remember that [&] does not keep variables alive, so a lambda that outlives its function must capture by copy.

for a middle

Explain init captures: a new closure member initialized at creation, deduced like auto, and the way to move a unique_ptr into a lambda.

for a senior

Treat any stored, returned or cross-thread lambda as a lifetime review point, and know which cases Clang's warning and AddressSanitizer catch and which they miss.

for a principal

Set the rule that deferred callbacks capture only owned state or explicitly guarded references, and back it with sanitizer builds in continuous integration.

## Why the click misbehaves A **by-reference capture** makes the lambda body refer to the original variable; the closure does not own it. The standard even leaves unspecified whether the closure stores anything for a reference capture. What it does say, in a note, is that invoking the lambda after the captured entity's lifetime has ended is likely to result in **undefined behaviour**. In the scenario, `make_save_handler` builds the Save button's handler from the dialog's locals and returns it. Its local `std::string title` has **automatic storage duration**: it is destroyed when the function returns. The handler survives, because the caller stores it for the next click. Every later click then reads a destroyed string. Nothing in the language promises a crash or a stale value: - the read may return whatever now occupies that stack memory; - it may crash, sometimes only in an optimized build; - it may print the right text for weeks, until an unrelated change reuses the memory. Built without a sanitizer, this snippet printed `saving` with an empty title at `-O0` and `saving` followed by a stray control byte at `-O2`: two outcomes of undefined behaviour, neither of them an answer. ## What the tools catch 1. **Clang 21** warned on the direct return: `address of stack memory associated with local variable 'title' returned [-Wreturn-stack-address]`, with a note that `title` was implicitly captured by reference. The warning sees only simple cases; a handler stored through a member or a container escapes it. 2. **AddressSanitizer**, built with `-fsanitize=address`, reported `stack-use-after-return` and named the frame and the variable. On macOS that check needs `ASAN_OPTIONS=detect_stack_use_after_return=1`; Clang's AddressSanitizer documentation says it is already enabled on Linux. Tools help, but the real fix is a capture that owns its data. ## Init captures: owning the state A **capture by copy** such as `[title]` gives the closure its own `std::string`, initialized when the lambda expression is evaluated. That is enough for cheap, copyable values. An **init capture**, available since C++14, goes further: `[name = expression]` declares a new closure member called `name`, with its type deduced as if by `auto name = expression;`, and initializes it when the lambda is created. That allows: - **moving** state in: `[d = std::move(draft)]` transfers a `std::unique_ptr<Draft>` into the closure, leaving the local `draft` empty; - **renaming** or computing: `[n = items.size()]` captures a value that is not itself a variable; - capturing **one member** of an object instead of the whole object: `[t = title]`. The fixed example returns a handler that copies `title` and moves the draft in, and it prints `saving Report: Q3 numbers` after the dialog's locals are gone. A by-reference init capture also exists, `[&r = x]`, but it is still a reference and dangles just the same. ## The trade-offs of owning | Capture | Owns its state? | Closure is copyable? | Cost | |---|---|---|---| | `[&]` or `[&title]` | no | yes | nothing, but dangles once the dialog's locals die | | `[title]` | yes | yes | one copy of the string | | `[d = std::move(draft)]` | yes | no: a `unique_ptr` member makes it move-only | one move | A closure holding a `std::unique_ptr` is **move-only**, so it cannot be put into a holder that requires copying. How callback wrappers deal with that is covered with invocable wrappers. ## Diagnosing it in a real codebase 1. Reproduce under AddressSanitizer; the report names the lambda's call operator and the frame that owned the dead variable. 2. Find the lambda's capture list and ask who calls the lambda, and when: during the creating function, or after it returns. 3. For each captured name, decide whether the handler needs the value at creation (copy it), needs to own a resource (move it in with an init capture), or needs the live object (pass a handle that can be checked, not a raw reference). 4. Replace capture defaults with an explicit list, so the next edit to the body cannot silently add another reference capture. ## How to answer State that `[&]` stores references whose targets die when the function returns, that calling the handler afterwards is undefined behaviour, and that sanitizers and Clang's warning catch only some cases. Then fix it: copy cheap values, and use an init capture to move expensive or move-only state into the closure.

  • Does a by-reference init capture such as [&r = config] solve the dangling problem?
    No. `[&r = config]` declares a reference member bound to `config`; it only renames the reference. If `config` is a local of the function that created the handler, `r` dangles after that function returns exactly as `[&config]` would. Only a by-copy capture or an init capture that copies or moves the value gives the closure its own state.
  • When is capturing locals by reference perfectly safe?
    When the lambda is called only while those locals are alive, typically when it is passed to a function that calls it before returning, such as `std::sort`'s comparator or a `for_each` visitor. The danger is a lambda that is stored, returned or handed to another thread and called after the enclosing scope has ended.

  • Capturing a local by reference keeps that local alive as long as the lambda.
  • Calling the handler after return just reads the last value the variable held.
  • [&] is safe because the compiler rejects any lambda that escapes its scope.
  • An init capture is evaluated each time the lambda is called.
  • [&r = title] gives the closure its own copy under a new name.