Pointer-to-Member QObject::connect, Context Lifetimes & Lambda Hazards

Replace runtime SIGNAL()/SLOT() strings with compile-time PMF QObject::connect calls, bind every C++20 lambda to an explicit context QObject *, and apply Qt::UniqueConnection.

30 minfree previewLinux 6.12→ module 3 lab
What you'll learn
  • Eliminate use-after-free and wrong-thread races in [this]-capturing lambdas by supplying the 4-argument receiver context QObject *.
  • Wire overloaded and prefix-argument member slots cleanly using qOverload<...>() and PMF QObject::connect.
  • Prevent duplicate slot invocations across repeated state transitions using Qt::UniqueConnection and QMetaObject::Connection handles.

The Number-One Use-After-Free Crash in Modern C++20 Qt 6 Codebases

Qt 4's string-based connect(src, SIGNAL(fault(int)), dst, SLOT(showFault(int))) deferred signature checking to runtime, turning typos into silent console warnings. Qt 6's pointer-to-member-function (PMF) syntax (connect(src, &Bus::fault, dst, &Panel::showFault)) verifies types at compile time and even lets a zero-argument slot like QWidget::update attach to a two-argument signal.

Yet C++20 lambdas introduced a subtle, devastating trap: the 3-argument overload connect(bus, &Bus::fault, [this] (int code) { m_label->setNum(code); });! Because no receiver QObject * was passed as a third argument, Qt attaches the lambda's lifetime ONLY to bus—AND executes the lambda on bus's thread! Close and delete your modal DiagnosticDialog while bus stays alive, emit one more fault, and the lambda dereferences freed this->m_label memory! Passing this as the 3rd context argument (connect(bus, &Bus::fault, this, [this]...)) cures both bugs in four characters.

fig_m03_l01_a.svg — Every lambda capturing widget state MUST pass a context…

Figure 3.1a. Every lambda capturing widget state MUST pass a context QObject* as the 3rd argument to QObject::connect.

mental model: A 3-argument lambda connect is like clipping a high-voltage test lead onto a removable PCB card without routing through the card-edge interlock connector: pull the card out of the chassis and the live lead arcs straight into an empty slot.

Where it stops working: Passing this as the 3rd context argument only protects this! If your lambda captures a SECOND independent raw pointer [this, otherDialog] and otherDialog dies while this stays alive, otherDialog will still dangle unless guarded with QPointer<QDialog>.

definition (Context QObject, Qt::AutoConnection, and Qt::UniqueConnection): In Qt 6's 4-argument functor overload QObject::connect(sender, &S::sig, context, functor, type), context is a const QObject * supplying two runtime properties: destruction lifetime (~QObject() on context destroys the functor QSlotObjectBase immediately) and thread affinity (Qt::AutoConnection compares QThread::currentThread() with context->thread(), posting a QMetaCallEvent when they differ). Qt::UniqueConnection (0x80) compares PMF QSlotObject addresses so re-running setup code never registers duplicate PMF connections.

ast_m03_l01.svg — Always pass a 3rd-arg context QObject* for lambdas; use…step 1/4
  1. Step 1. Use 4-argument directly whenever a member slot matches or accepts a prefix of signal args.
  2. Step 2. Wrap overloaded Qt methods such as QWidget::update or QSpinBox::valueChanged in qOverload<Args...>().
  3. Step 3. Always pass 'this' (or the captured widget) as the 3rd context argument before any capturing lambda.
  4. Step 4. Pass Qt::UniqueConnection on idempotent PMF binds, or store ::Connection for lambdas.

Figure 3.1b. Always pass a 3rd-arg context QObject* for lambdas; use Qt::UniqueConnection on PMFs.

Inside QSlotObjectBase, Prefix Arity Dropping & UniqueConnection

How does Qt 6 invoke a C++20 lambda or member pointer without moc knowing the lambda's signature? Instead of routing through qt_static_metacall, template QObject::connect allocates a tiny polymorphic QtPrivate::QFunctorSlotObject (or QCallableObject) node holding a static function pointer (impl) and the closure by value. During QMetaObject::activate, Qt passes void **_a straight into that QSlotObjectBase node, which unpacks only the prefix 0..K arguments the callable expects!

Now understand why Qt::UniqueConnection works on &DiagnosticPopup::refreshBadge in pmf_lifetime_panel.cpp below, yet CANNOT deduplicate two calls to connect(..., [this]{ ... })! Under the ISO C++20 standard, every lambda expression has a unique anonymous closure type, and even calling the same helper function twice creates two distinct QFunctorSlotObject instances without comparable member-function addresses. Use PMFs when you need Qt::UniqueConnection, or hold a QMetaObject::Connection member and disconnect prior to reconnecting!

fig_m03_l01_b.svg — Dual-linked Connection nodes let either ~Sender() or…

Figure 3.1b. Dual-linked Connection nodes let either ~Sender() or ~Context() sever a slot in O(1) list manipulation.

QObject::connect FormCompile-Time Type CheckReceiver Delete SafetyWorker -> GUI Thread Safe
Legacy SIGNAL() / SLOT() macrosNone (checked at runtime only)Yes (dst is a QObject *)Yes (dst->thread() known)
3-arg connect(src, &S::sig, [this]{...})Yes (C++20 template traits)NO — dangles after ~this()!NO — runs on src worker thread!
4-arg connect(src, &S::sig, this, [this]{...})Yes (prefix args allowed)Yes (severed in ~QObject())Yes (queues onto this->thread())
4-arg PMF + Qt::UniqueConnectionYes (exact + implicit conversions)Yes + rejects duplicate bindsYes (`AutoConnectionUniqueConnection`)
learner@ksa: ~/gl-q01/m03-l01
learner@ksa:~/gl-q01/m03-l01$ bat -H 29 -H 35 pmf_lifetime_panel.cpp File: pmf_lifetime_panel.cpp    #include <QLabel>    #include <QMetaObject>    #include <QObject>    #include <QString>    #include <QWidget>        namespace hmi {        class TelemetryBus : public QObject {        Q_OBJECT    public:        explicit TelemetryBus(QObject *parent = nullptr) : QObject(parent) {}    signals:        void faultRaised(int code, const QString &subsystem);        void tareCaptured(int milliVolts);    };        class DiagnosticPopup final : public QWidget {        Q_OBJECT    public:        DiagnosticPopup(TelemetryBus *bus, QWidget *parent = nullptr)            : QWidget(parent), m_badge(new QLabel(this)) {            bindBus(bus);            bindBus(bus); // Idempotent: UniqueConnection prevents double PMF bind!        }            void bindBus(TelemetryBus *bus) {            // 1. PMF + UniqueConnection + prefix arity (2-arg signal -> 0-arg update)          connect(bus, &TelemetryBus::faultRaised,                    this, qOverload<>(&QWidget::update),                    static_cast<Qt::ConnectionType>(Qt::AutoConnection | Qt::UniqueConnection));                // 2. 4-arg context-bound lambda (disconnects old handle before re-binding)            QObject::disconnect(m_faultConn);          m_faultConn = connect(                bus, &TelemetryBus::faultRaised, this,                [this] (int code, const QString &sub) {                    m_badge->setText(QStringLiteral("[%1] %2").arg(code).arg(sub));                });                // 3. One-shot calibration capture auto-severed on first fire OR ~Popup()            QObject::disconnect(m_tareConn);            m_tareConn = connect(                bus, &TelemetryBus::tareCaptured, this,                [this] (int mv) {                    m_tareMv = mv;                    QObject::disconnect(m_tareConn);                });        }        private:        QLabel *m_badge = nullptr;        QMetaObject::Connection m_faultConn;        QMetaObject::Connection m_tareConn;        int m_tareMv = 0;    };        } // namespace hmi
  1. qOverload<>(&QWidget::update) selects 0-arg update() and Qt::UniqueConnection deduplicates repeated bindBus() calls.
  2. Passing 'this' as the 3rd context argument prevents use-after-free when DiagnosticPopup closes while TelemetryBus lives on.
QObject-connect(3qt) at a glance — GL-Q01
QObject-connect(3qt)        GL-Q01 Quick Reference        QObject-connect(3qt) NAME       QObject::connect, QObject::disconnect, qOverload - PMF & functor       lifetime rules SYNOPSIS       QMetaObject::Connection QObject::connect(        const QObject *sender, PointerToMemberFunction signal,        const QObject *context, Functor functor,        Qt::ConnectionType type = Qt::AutoConnection);        LIFETIME & THREADING RULES 1. Always supply 'context' when 'functor'       captures widget/object pointers: - Destroying 'context' disconnects the       slot automatically. - Qt::AutoConnection queues onto context->thread()       when emitted cross-thread. 2. Qt::UniqueConnection deduplicates       identical PMF pairs; for lambdas, store QMetaObject::Connection and       call QObject::disconnect(handle). Kernel Systems Academy             Lesson 3.1             QObject-connect(3qt) GL-Q01 quick reference · full manual page: man 3qt QObject-connect 

Verifying Context Auto-Prune, UniqueConnection & 3-Arg Hazards in C++20

In verify.cpp, we implement a C++20 Signal<Args...> dispatcher tracking ContextObject std::weak_ptr<bool> lifetime tokens, PMF (receiver, slot_tag) UniqueConnection deduplication, one-shot disconnect(conn_id) handles, and the 3-argument contextless hazard.

Follow the assertions in main(): calling connect_pmf twice with unique = true registers only one slot (popup.hits == 2 across two emissions, not 4), destroying popup auto-prunes both its PMF and 4-arg lambda slots on the next emission, whereas connect_3arg_hazard fires into dead scope (dangling_fires == 1)!

learner@ksa: ~/gl-q01/m03-l01
learner@ksa:~/gl-q01/m03-l01$ bat -H 27 -H 73 verify.cpp File: verify.cpp    #include <algorithm>    #include <cassert>    #include <cstdio>    #include <functional>    #include <memory>    #include <vector>        namespace hmi {        class ContextObject {    public:        ContextObject() : m_alive(std::make_shared<bool>(true)) {}        virtual ~ContextObject() { *m_alive = false; }        ContextObject(const ContextObject &) = delete;        ContextObject &operator=(const ContextObject &) = delete;        std::weak_ptr<bool> token() const noexcept { return m_alive; }        private:        std::shared_ptr<bool> m_alive;    };        template <typename... Args>    class Signal {    public:        template <typename Recv>        int connect_pmf(Recv *rx, void (Recv::*pmf)(Args...), int pmf_tag,                      bool unique_conn = false) {            if (unique_conn) {                for (const auto &s : m_slots) {                    if (s.active && s.rx_ptr == rx && s.pmf_tag == pmf_tag) {                        return 0; // Qt::UniqueConnection rejected duplicate!                    }                }            }            const int id = m_next_id++;            m_slots.push_back({id, rx, pmf_tag, true, rx->token(), true,                               [rx, pmf] (Args... a) { (rx->*pmf)(a...); }});            return id;        }            template <typename Fn>        int connect_4arg(const ContextObject *ctx, Fn &&fn) {            const int id = m_next_id++;            m_slots.push_back({id, ctx, -1, true, ctx->token(), true,                               std::function<void(Args...)>(std::forward<Fn>(fn))});            return id;        }            template <typename Fn>        int connect_3arg_hazard(Fn &&fn) {            const int id = m_next_id++;            m_slots.push_back({id, nullptr, -1, false, {}, true,                               std::function<void(Args...)>(std::forward<Fn>(fn))});            return id;        }            bool disconnect(int id) noexcept {            for (auto &s : m_slots) {                if (s.id == id && s.active) {                    s.active = false;                    return true;                }            }            return false;        }            void emit_sig(Args... args) {            const std::size_t n = m_slots.size();            for (std::size_t i = 0; i < n; ++i) {                if (!m_slots[i].active) {                    continue;                }              if (m_slots[i].has_ctx) {                    auto sp = m_slots[i].life.lock();                    if (!sp || !*sp) {                        m_slots[i].active = false;                        continue;                    }                }                m_slots[i].fn(args...);            }            m_slots.erase(                std::remove_if(m_slots.begin(), m_slots.end(),                               [] (const Entry &e) { return !e.active; }),                m_slots.end());        }            std::size_t active_count() const noexcept { return m_slots.size(); }        private:        struct Entry {            int id;            const ContextObject *rx_ptr;            int pmf_tag;            bool has_ctx;            std::weak_ptr<bool> life;            bool active;            std::function<void(Args...)> fn;        };        int m_next_id = 1;        std::vector<Entry> m_slots;    };        class Popup final : public ContextObject {    public:        void on_fault(int code) { sum += code; ++hits; }        int sum = 0;        int hits = 0;    };        } // namespace hmi        int main() {        hmi::Signal<int> fault_sig;        int safe_ctx_sum = 0;        int one_shot_count = 0;            {            hmi::Popup dlg;            assert(fault_sig.connect_pmf(&dlg, &hmi::Popup::on_fault, 1, true) > 0);            assert(fault_sig.connect_pmf(&dlg, &hmi::Popup::on_fault, 1, true) == 0);                fault_sig.connect_4arg(&dlg, [&] (int c) { safe_ctx_sum += c; });            int once_id = 0;            once_id = fault_sig.connect_4arg(&dlg, [&] (int) {                ++one_shot_count;                fault_sig.disconnect(once_id);            });                fault_sig.emit_sig(10);            fault_sig.emit_sig(25);            assert(dlg.hits == 2 && dlg.sum == 35);            assert(safe_ctx_sum == 35 && one_shot_count == 1);        }            // dlg is now destroyed: 4-arg and PMF slots must auto-prune!        fault_sig.emit_sig(100);        assert(safe_ctx_sum == 35 && fault_sig.active_count() == 0);            int dangling_fires = 0;        {            hmi::Popup transient;            (void)transient;            fault_sig.connect_3arg_hazard([&] (int) { ++dangling_fires; });        }        fault_sig.emit_sig(404);        assert(dangling_fires == 1);            std::printf("PMF unique_dup=0 ctx_sum=%d one_shot=%d pruned=%zu uaf_3arg=%d\n",                    safe_ctx_sum, one_shot_count,                    fault_sig.active_count(), dangling_fires);        return 0;    }
  1. unique_conn rejects duplicate (rx_ptr, pmf_tag) registration and returns null handle 0, matching Qt::UniqueConnection.
  2. Expired receiver life token marks the connection inactive instead of invoking a dangling [this] closure.

Confirming UniqueConnection Deduplication and Context Pruning

Verify ./verify prints PMF unique_dup=0 ctx_sum=35 one_shot=1 pruned=0 uaf_3arg=1. Passing unique_conn = true rejected the duplicate Popup::on_fault registration (0), destroying dlg kept ctx_sum frozen at 35 when 100 was emitted (pruned=0), and the 3-argument contextless lambda proved why omitting a context object fires into destroyed state (uaf_3arg=1).

Make this a zero-exception team lint rule: grep every connect( call in pull requests and require a 4th argument whenever the 3rd argument begins with [!

learner@ksa: ~/gl-q01/m03-l01
learner@ksa:~/gl-q01/m03-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m03-l01./verifyPMF unique_dup=0 ctx_sum=35 one_shot=1 pruned=1 uaf_3arg=1learner@ksa:~/gl-q01/m03-l01
strace — learner@ksa: ~/gl-q01/m03-l01
learner@ksa:~/gl-q01/m03-l01strace -e trace=write,exit_group ./verifywrite(1, "PMF unique_dup=0 ctx_sum=35 one_"..., 59) = 59exit_group(0)                           = ?+++ exited with 0 +++

Qt::UniqueConnection on Lambdas & Multi-Pointer Capture Traps

With 4-argument context-bound QObject::connect and Qt::UniqueConnection in your toolkit, signal connections become both compile-time type-checked and teardown-safe.

Next, Lesson 3.2 traces what happens underneath queued connections and user input: how QCoreApplication::exec() drives the event loop, why postEvent and sendEvent have opposite memory-ownership rules, and how installEventFilter intercepts events in LIFO order.

Passing Qt::UniqueConnection to a Lambda QObject::connect Call:

  • Symptom: In Qt 6, passing Qt::UniqueConnection to a lambda connect(src, &S::sig, this, [this]{...}, Qt::UniqueConnection) fails compilation (static_assert in Qt 6.8 or returns invalid connection) instead of deduplicating.
  • Root Cause: Each C++ lambda closure type is unique and lacks a comparable member-function pointer address, so Qt cannot test whether two functor objects represent the 'same' slot.
  • Fix: Promote the lambda body to a private member function (&MyWidget::updateStatus) when using Qt::UniqueConnection, or store QMetaObject::Connection and disconnect the prior handle before reconnecting.

Capturing [&] Reference-to-Stack-Locals Inside an Asynchronous Slot Lambda:

  • Symptom: Writing int threshold = 80; connect(timer, &QTimer::timeout, this, [&] { check(threshold); }); inside a constructor crashes or reads garbage when timeout fires 50 ms later!
  • Root Cause: Constructor stack local threshold dies as soon as the constructor returns, leaving [&] holding a dangling stack reference even though this is still alive!
  • Fix: Never use default by-reference capture [&] in signal lambdas! List explicit value/pointer captures ([this, threshold]) so stack scalars are copied into the closure.

Guided Practice

Extend Signal in verify.cpp to support prefix-argument binding (Signal<int, int>::connect_0arg(ctx, fn)), allowing a zero-argument callback [] { ... } to attach to a (int code, int severity) signal just like qOverload<>(&QWidget::update) in Qt 6.

Independent Practice

Audit a multi-dialog HMI workflow where a temporary CalibrationWizard connects to a singleton SensorManager AND references a sibling StatusFooter *footer. Show how to combine this as the 3rd connect context argument with QPointer<StatusFooter> safeFooter = footer; captured by value so destroying EITHER widget first is 100% memory-safe.

Verification Checks

quiz · 1 of 3

A background worker QThread emits reader->packetReady(buf) connected via 3-argument connect(reader, &Reader::packetReady, [label] (const QByteArray &b) { label->setText(...); }). On which thread does label->setText(...) execute?

quiz · 2 of 3

Why does connect(bus, &TelemetryBus::faultRaised, this, qOverload<>(&QWidget::update)) compile cleanly even though faultRaised(int, const QString &) emits two arguments and update() accepts zero?

quiz · 3 of 3

When bindBus(bus) may be called multiple times during runtime profile reloads, how does Qt::UniqueConnection behave on connect(bus, &Bus::fault, this, &Panel::onFault, Qt::UniqueConnection)?

Key takeaways

  • Three-argument QObject::connect(sender, &S::sig, lambda) binds connection lifetime solely to sender, causing a fatal use-after-free crash if lambda captures [this] on a shorter-lived receiver QWidget.
  • Four-argument QObject::connect(sender, &S::sig, receiver, lambda) ties the connection to both endpoints so ~QObject() on receiver disconnects the closure automatically and Qt::AutoConnection queues onto receiver's thread.
  • Pointer-to-member QObject::connect verifies parameter conversions at compile time via QtPrivate::FunctionPointer traits and permits slots to accept a shorter prefix of the signal's arguments.
  • Passing Qt::UniqueConnection bitwise-ORed into connection flags deduplicates identical (sender, &S::sig, receiver, &R::slot) PMF pairs, whereas anonymous C++ lambdas have distinct closure types and require explicit handle tracking.
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure