ProblemsUB & GotchasThe lambda that outlives its capture
IntermediateUB & Gotchas

The lambda that outlives its capture

Context

The callback factory worked perfectly through the entire demo sprint. In prod the counters started returning numbers from a parallel universe — only under load, and only on Fridays. A genre classic: the lambda captured a local by reference and outlived it. A closure should own its state, not sublet someone else's stack.

Task

makeCounter returns a lambda that captures the local count by reference — but count dies when makeCounter returns. Every later call reads and writes a dead stack slot (undefined behaviour). Fix the capture.

Constraints

  • The lambda must capture its state by value and own it
  • The returned counter yields 1, 2, 3, … on successive calls
  • Counters from separate makeCounter() calls are independent
  • No globals/statics as a workaround

Before you code

  • What does a by-reference capture actually store inside the closure object?
  • Why does the by-value version need the mutable keyword?
  • When is a by-reference capture the right choice, and what is the rule of thumb for lifetimes?

Tests

  • #1Counter counts 1, 2, 3
  • #2Independent counters do not share state

Hints

Hint 1

Capture by value: [count]. The closure then owns its own copy of the counter.

Hint 2

By-value captures are const inside the call operator by default — add mutable: [count]() mutable { return ++count; }.

Editordangling-lambda-capture.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.