skip to content

A C++ desktop app crashes when a queued save callback fires after the user closed its window; why does capturing this cause this, and how do you fix it?

level: seniorimportance: should knowfreq 52%

answer

  1. what the closure actually stores
  2. a raw pointer to the window
  3. the queue outlives the window
  4. cancel on destruction
  5. or check liveness before use

basics

~20 s

A lambda that captures this stores only the window's address. When the window is destroyed before the queue runs the callback, the lambda reads freed memory: use-after-free. Cancel pending callbacks in the destructor, or let the callback check that the window is alive.

solid answer

~50 s

A lambda written `[this] { ... }` captures the `this` pointer by copy — a raw pointer — and implicitly accesses members through it. Nothing about the capture extends the window's lifetime. The callback is stored in an event queue, a timer or a network library that outlives the window; when the user closes the window, its destructor runs and its memory is freed, yet the queue still holds the lambda. When it fires, `title_` is read through a dangling `this`: undefined behaviour, which may print stale text, show a wrong title or crash far from the close handler. `[=]` is no safer: it captures `this` implicitly (deprecated since C++20). Fixes: the window cancels its pending callbacks in its destructor, using the handle the queue returned, or the callback captures something that can report whether the window still exists, such as a `std::weak_ptr` when a `std::shared_ptr` owns the window, and returns early if not.

code

cpp · 26 lines
cpp
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

std::vector<std::function<void()>> pending;   // stands in for the UI event queue

class Window {
public:
    explicit Window(std::string t) : title_(std::move(t)) {}
    void onSaveClicked() {
        pending.push_back([this] {             // stores the address of this Window
            std::cout << "saved " << title_ << '\n';
        });
    }
private:
    std::string title_;
};

int main() {
    auto w = std::make_unique<Window>("report.txt");
    w->onSaveClicked();
    w.reset();                                 // user closed the window
    for (auto& task : pending) task();         // the callback reads a freed Window
}

go deeper

for a junior

Recall that [this] stores a pointer to the object, not the object, so the lambda must not run after the object is destroyed.

for a middle

Explain how [=] also captures this, what [*this] changes, and why copying the members the callback needs removes the dependency.

for a senior

Diagnose the crash report: the stack points into the queue or string code, the culprit is the stored closure, and the fix is revocation or a liveness check.

for a principal

Set the codebase rule for asynchronous callbacks: every API that stores a callback returns a handle, and every object that posts one owns that handle's cancellation.

## What `[this]` captures A lambda's capture list decides which data the closure object stores. Inside a member function, `this` is a prvalue of type `Window*`, and `[this]` copies that pointer into the closure. Every unqualified use of a member inside the lambda body, such as `title_`, is rewritten to `this->title_`. So the closure carries a **raw pointer** to the window and nothing else. It does not copy the window, and it does not keep it alive. This is the C++-specific twist: in languages with tracing garbage collection a closure that refers to an object keeps that object reachable, whereas a C++ closure holding `this` behaves exactly like a stored `Window*`. ## How the crash happens 1. The user clicks Save; `onSaveClicked` posts `[this] { ... }` to the UI event queue. 2. Before the queue drains, the user closes the window; the owning code destroys the `Window`, running its destructor and freeing its storage. 3. The event loop runs the queued closure. It reads `this->title_`, an object inside freed memory. Step 3 is a **use-after-free**, which is undefined behaviour. The visible effect varies: - the old bytes are intact and the save "works" with the right title; - the allocator reused the block, so the callback reads another object's fields; - a member such as `std::string` was destroyed, so its heap pointer is stale and dereferencing it crashes inside library code; - the crash report points into the event loop or the string class, not at the close handler. ## Variants of the same bug | Capture | What is stored | Safe after the window dies? | |---|---|---| | `[this]` | `Window*` | no | | `[=]` in a member function | `Window*` (implicit capture of this, deprecated since C++20) | no | | `[&]` in a member function | `this` plus references to locals | no, and the locals dangle too | | `[*this]` (C++17) | a copy of the whole `Window` | the copy is safe, but it no longer updates the real window | | `[title = title_]` | a copy of one member | yes, for that member | Copying only what the callback needs is often the simplest repair when the callback does not have to touch the live window. ## Repairs that keep the behaviour - **Revoke on destruction.** Store the handle that the queue, timer or signal connection returns, and cancel it in the destructor. The window then guarantees no callback outlives it. This works for any ownership model, but every posting site must record its handle. - **Check liveness in the callback.** If the window is owned by a `std::shared_ptr`, capture a `std::weak_ptr` and lock it at the start of the callback; if the window is gone the callback returns. The material on shared and weak pointers covers the mechanics. - **Run callbacks on the owner's thread and drain before destruction.** Some UI frameworks offer a per-object context so that destroying the object discards its queued work; using that facility is the framework-specific form of the first fix. With threads involved, revoking is only correct if cancellation and execution are synchronised, otherwise the callback can already be running while the destructor proceeds. ## Choosing between the fixes | Fix | Works when | Cost | |---|---|---| | cancel in the destructor | the queue returns a handle and runs on the same thread | every posting site must store its handle | | weak liveness check | the object is owned by `std::shared_ptr` | shared ownership for an object that may not need it | | copy the needed members | the callback does not need the live object | the callback cannot update the window | In UI code the first fix is usually the most natural, because the window already has a clear owner and a clear moment of death, and the toolkit's timers and signal connections typically return a handle that can be disconnected. ## Reviewing for it - Look for `[this]`, `[=]` and `[&]` lambdas passed to anything that stores them: queues, timers, async I/O, thread pools, signal connections. - Ask who owns the callback and who owns the object, and whether the first can outlive the second. - Confirm the destructor cancels, or that the callback can detect the object's death.

  • Does capturing [*this] solve the problem?
    It removes the dangling access, because the closure holds its own copy of the window (C++17). But the callback now works on a snapshot: changes it makes never reach the live window, copying may be expensive, and non-copyable types cannot be captured that way. It suits read-only callbacks that only need the window's data, not the window.
  • Why is revoking in the destructor not enough when callbacks run on another thread?
    The callback may already be executing when the destructor calls cancel. Unless cancellation waits for a running callback, or both are serialised on one thread or under one lock, the destructor frees members the callback is still reading. Correct revocation means cancel-and-wait, or posting the destruction itself onto the callback's thread.

  • Capturing this keeps the object alive until the lambda is destroyed.
  • Using [=] instead of [this] copies the object, so it is safe.
  • The crash is in the event loop, so the bug must be in the event loop.
  • A null check on this inside the lambda detects the destroyed window.
  • It printed the right title in testing, so the callback is safe.