A C++ dialog's member function returns a [=] lambda reading its member title for a button; why does a click after the dialog is destroyed crash, and how do you fix it?
answer
- members are reached through this
- [=] copies the pointer, not the object
- deprecated implicitly since C++20
- [*this] copies the whole object
- weak_from_this and lock at call time
basics
~20 sA member name inside the lambda means this->title, so [=] captures the this pointer, not a copy of title. Once the dialog is destroyed the pointer dangles. Capture the member by value, copy the object with [*this], or guard the call with a weak_ptr.
solid answer
~50 sInside a member function, a data member such as `title` is really `this->title`, so `[=]` implicitly captures `*this` by reference, which in practice stores the `this` pointer. The closure never copies `title`; it reads it through the pointer at call time. If the button outlives the dialog, the click dereferences a destroyed object: undefined behaviour, which AddressSanitizer reports as `heap-use-after-free`. Because `=` suggests a copy that never happens, **C++20 deprecated** the implicit capture of `this` through `[=]`; Clang warns with `-Wdeprecated-this-capture` and suggests `[=, this]`. Fixes depend on intent: capture just the member, `[t = title]`; copy the whole object with **C++17** `[*this]`; or, when the dialog is owned by a `std::shared_ptr`, capture `weak_from_this()` and `lock()` it on each click so a closed dialog is skipped. Unregistering the callback in the dialog's destructor also works.
code
cpp · 16 lines#include <cstdio>
#include <string>
struct Dialog {
std::string title = "Export";
auto save_handler() {
return [=, this] { std::printf("saving %s\n", title.c_str()); }; // stores this
}
};
int main() {
auto* d = new Dialog;
auto on_save = d->save_handler();
delete d; // the dialog closes; the handler still holds the pointer
on_save(); // undefined behaviour: reads a destroyed Dialog
}go deeper
Remember that a member used inside a lambda is reached through this, so the lambda depends on the object staying alive.
Explain the capture forms: implicit this through [=] or [&], explicit [this], C++17 [*this], and init captures of single members.
Diagnose the use-after-free from an AddressSanitizer report, then choose between copying state, weak_ptr locking and disconnecting in the destructor based on ownership.
Decide the event system's ownership contract, such as connection handles or weak references, so that callbacks outliving their objects are impossible by construction.
## Why [=] does not copy the member Inside a non-static member function, a bare data member name such as `title` is shorthand for `this->title`. For capture purposes the standard counts that use as a reference to the object `*this`. With a `=` default, the lambda therefore captures `*this` **by reference**, which in practice means it stores the `this` pointer. It does not make a copy of `title`, however much the `=` suggests one. The closure is now only as valid as the object. A button that outlives its dialog calls the handler after `delete`, and the read of `title` goes through a dangling pointer. That is **undefined behaviour**: the click may crash, print garbage, or print the old title until the memory is reused. Built with `-fsanitize=address`, the example reports `heap-use-after-free` and points at the lambda's call operator and at the `delete` in `main`. ## What changed in C++17 and C++20 | Form | What the closure holds | Since | |---|---|---| | `[=]` naming a member | the `this` pointer, captured implicitly | C++11; **deprecated in C++20** | | `[this]` or `[=, this]` | the `this` pointer, captured explicitly | `[this]` C++11; `[=, this]` C++20 | | `[&]` naming a member | the `this` pointer, captured implicitly | C++11, not deprecated | | `[*this]` | a copy of the whole object | C++17 | | `[t = title]` | a copy of one member | C++14 | C++20 deprecated only the `=` case, because `=` reads as "by value" yet captures a pointer. Compiled as C++20, Clang 21 printed `implicit capture of 'this' with a capture default of '=' is deprecated [-Wdeprecated-this-capture]` and offered the fix-it `, this`. Spelling `[=, this]` makes the pointer capture explicit but does **not** make it safe; under `-std=c++17` Clang accepts it only as a C++20 extension. ## Choosing a fix 1. **Copy what the handler needs.** `[t = title]` copies one member when the lambda is created. It is cheap and has no lifetime coupling, but the handler will not see later changes to the dialog's title. 2. **Copy the whole object** with `[*this]` (C++17). The closure gets its own `Dialog`, which can be expensive, fails to compile for a non-copyable class, and is equally a snapshot. 3. **Observe the live object safely.** When the dialog is owned by a `std::shared_ptr`, derive it from `std::enable_shared_from_this` and capture `weak = weak_from_this()` (C++17). On each click, `weak.lock()` yields a `std::shared_ptr` that keeps the dialog alive for the duration of the call, or an empty one if it is gone, so the click can be ignored. The third code example prints `dialog closed, click ignored` after the dialog is released. 4. **Capturing `shared_from_this()` strongly** keeps the dialog alive for as long as the button holds the handler. If the dialog also owns the button, that is a reference cycle, and neither is ever destroyed. 5. **Disconnect on destruction.** If the event system returns a connection handle, store it in the dialog and disconnect in the destructor, so no handler can run after the object dies. ## Where the same bug appears The button is one case of a general shape: a lambda that names members and is stored somewhere that outlives the object. - timers and delayed tasks posted from a member function; - thread-pool jobs and network completion handlers that run on another thread after the object is gone; - observers registered with a longer-lived subject. `[&]` naming a member has the same problem, since it too captures `this` implicitly; it simply draws no deprecation warning. ## Mistakes interviewers listen for - Saying `[=]` copies members. It copies the `this` pointer. - Treating `[=, this]` or `[this]` as a fix; they only make the same pointer capture explicit. - Reaching for `[*this]` without noticing the cost of copying a large or non-copyable object. - Capturing `shared_from_this()` in a handler owned by the same object and creating a leak. - Calling `shared_from_this()` or `weak_from_this()` in a constructor, before any `std::shared_ptr` owns the object. ## How to answer Explain that member access goes through `this`, so `[=]` stores a pointer, and that C++20 deprecated that implicit form. Then pick a fix by intent: copy the data you need, copy the object with `[*this]`, or hold a `std::weak_ptr` and lock it per call, and mention disconnecting callbacks in the destructor.
- Why does [*this] fail to compile for some classes?`[*this]` copy-initializes a closure member from the current object, so the class must be copy-constructible. A dialog holding a `std::unique_ptr`, a `std::mutex` or any other non-copyable member cannot be captured that way. Capture only the members you need with init captures, or use a `std::weak_ptr` to observe the live object instead.
- What does weak.lock() buy you over checking weak.expired() first?`expired()` followed by a separate access is a race when another thread can release the last owner in between. `lock()` atomically returns a `std::shared_ptr` that keeps the object alive for as long as you hold it, or an empty pointer if it is already gone, so the check and the use cannot be separated.
- [=] inside a member function copies the data members the body uses.
- Writing [=, this] instead of [=] fixes the dangling handler.
- C++20 removed implicit this capture, so old code no longer compiles.
- [*this] stores a reference that keeps the object alive.
- Capturing shared_from_this() is always safe, whatever owns the handler.
Assumes C++20 or later: [*this] arrived in C++17, and C++20 deprecated implicit capture of this through [=] and allowed [=, this].