Virtual Dispatch, Inheritance, Operator Overloads & C++20 Concepts

Balance dynamic vptr/vtable interfaces at QObject UI boundaries with value-type operator overloads (operator<=>) and zero-overhead C++20 concept pipelines on hot sensor paths.

30 minfree previewLinux 6.12→ module 1 lab
What you'll learn
  • Measure exact object size (sizeof) growth from vptr insertion and verify base-pointer polymorphic teardown via virtual destructors.
  • Implement constexpr C++20 value-type operator overloads (operator<=>, operator==, operator+) cleanly separated from identity-based QObject classes.
  • Partition high-rate C++20 concept-constrained sample filters from non-templated QObject presenters and benchmark dispatch latency with CLOCK_MONOTONIC.

Dynamic Widget Polymorphism Meets Zero-Overhead C++20 Static Constraints

Every QObject instance begins in memory with a hidden virtual table pointer (vptr: 8 bytes on LP64 x86_64, 4 bytes on ILP32 ARMv7-A) followed by QScopedPointer<QObjectData> d_ptr. That vptr makes heterogeneous UI trees possible: a QVBoxLayout holds QWidget * pointers and dispatches sizeHint(), event(QEvent *), and ~QWidget() dynamically through each subclass's vtable. Yet calling a virtual method inside a 20 kHz ADC sample loop forces an indirect call (call *[rax + offset]) on every sample and blocks loop vectorization.

Simultaneously, moc enforces a hard architectural rule: a Q_OBJECT class cannot be a class template (template <typename T> class Plot : public QWidget { Q_OBJECT }; fails moc compilation), because moc runs prior to C++ template instantiation and emits a single staticMetaObject table. C++20 resolves both tensions cleanly: model physical units as constexpr value types with operator<=>, run hot-loop math through C++20 concept function templates, and emit decimated updates from a final concrete QObject presenter!

fig_m01_l03_a.svg — Keep arithmetic and filtering in constexpr value types…

Figure 1.3a. Keep arithmetic and filtering in constexpr value types and C++20 concepts; cross into /QObject dispatch only at frame cadence.

mental model: Dynamic vtable dispatch works like routing calls through a live telephone switchboard where any extension can be patched to a new desk at runtime, whereas a C++20 concept acts like a precision-keyed waveguide machined directly into the chassis after verifying flange dimensions on the blueprint.

Where it stops working: A machined waveguide cannot re-route to a plugin loaded at runtime via dlopen(), so genuinely heterogeneous runtime collections—such as child widgets in a layout or swappable hardware backends—still require a vptr and a virtual base destructor.

definition (vptr, vtable, and C++20 Concepts): Under the Itanium C++ ABI used on Linux (x86_64 and ARMv7-A), every polymorphic object stores a hidden vptr at byte offset 0 addressing a compiler-generated read-only vtable containing RTTI metadata and function pointers for virtual methods and deleting/complete destructors. A C++20 concept is a named compile-time boolean predicate (requires(...)) over template parameters that validates syntactic and type requirements at instantiation time with clear diagnostics and zero runtime storage or indirection.

ast_m01_l03.svg — Use virtual + override/final for runtime…step 1/4
  1. Step 1. Declare a public virtual destructor on every abstract base class deleted through a base pointer.
  2. Step 2. Mark derived virtual implementations with override and seal concrete leaf classes with final.
  3. Step 3. Give strongly typed scalar wrappers constexpr operator<=> and constrain DSP loops with C++20 concepts.
  4. Step 4. Place template <SampleFilter F> on a normal member function of a concrete Q_OBJECT presenter.

Figure 1.3b. Use virtual + override/final for runtime plugins/widgets, and C++20 concepts + <=> for hot data.

Inside Itanium C++ ABI Object Layout and Concept Instantiation

Inspect telemetry_sink.hpp below. MilliVolts wraps a std::int32_t with zero vptr, so sizeof(MilliVolts) == 4 and arrays pack contiguously in L1 cache. Defaulting constexpr auto operator<=>(const MilliVolts &) const noexcept = default; synthesizes all six relational operators (==, !=, <, <=, >, >=) in one line, while operator+ prevents accidentally adding raw MilliAmps to MilliVolts!

Next, look at how TelemetryPresenter works around moc's no-class-template rule: TelemetryPresenter itself is a concrete final QObject subclass, so moc happily generates its staticMetaObject and meanUpdated(std::int32_t) signal. Meanwhile, processBurst<F> is a regular C++20 SampleFilter-constrained member function template (NOT marked as a slot or signal), allowing g++ to inline the entire burst accumulation loop before emitting one change-guarded UI signal!

fig_m01_l03_b.svg — Adding the first virtual function inserts an 8-byte…

Figure 1.3b. Adding the first virtual function inserts an 8-byte vptr (plus alignment padding) on LP64 hosts or 4 bytes on ARMv7-A.

Polymorphism / Type MechanismPer-Object Memory CostCall Resolution & InliningBest Fit in Qt 6 HMIs
virtual Base + override+8 B vptr (x86_64) / +4 B (ARMv7-A)Runtime vtable load; blocks cross-TU inliningHeterogeneous QWidget trees, QAbstractItemModel, plugins
virtual Leaf Marked final+8 B / +4 B vptr (inherited)Devirtualized direct call when static type is the final leafConcrete MainWindow, TelemetryPresenter, custom gauges
C++20 concept Template0 B (sizeof holds payload only)100% compile-time bound; eligible for SIMD auto-vectorizationADC ring-buffer filters, CRC framing, fixed-point DSP
C++20 Value operator<=> / +0 B overhead over underlying scalarconstexpr inline register instructionsStrongly typed units (MilliVolts, MicroAmps, KiloPascals)
learner@ksa: ~/gl-q01/m01-l03
learner@ksa:~/gl-q01/m01-l03$ bat -H 13 -H 35 telemetry_sink.hpp File: telemetry_sink.hpp    #pragma once    #include <QObject>    #include <compare>    #include <concepts>    #include <cstdint>    #include <span>        namespace hmi {        struct MilliVolts {        std::int32_t mv = 0;          constexpr auto operator<=>(const MilliVolts &) const noexcept = default;        constexpr MilliVolts operator+(MilliVolts rhs) const noexcept {            return MilliVolts{mv + rhs.mv};        }    };        template <typename F>    concept SampleFilter = requires(F filter, const F cfilter, MilliVolts sample) {        { filter.push(sample) } noexcept -> std::same_as<void>;        { cfilter.mean() } noexcept -> std::same_as<MilliVolts>;    };        template <SampleFilter F>    inline MilliVolts ingest_burst(F &filter, std::span<const MilliVolts> burst) noexcept {        for (MilliVolts s : burst) {            filter.push(s);        }        return filter.mean();    }        class ITelemetryBackend {    public:      virtual ~ITelemetryBackend() = default;        virtual MilliVolts readChannel(int ch) const noexcept = 0;    };        class TelemetryPresenter final : public QObject {        Q_OBJECT    public:        explicit TelemetryPresenter(QObject *parent = nullptr) : QObject(parent) {}            template <SampleFilter F>        void processBurst(F &filter, std::span<const MilliVolts> samples) {            const MilliVolts avg = ingest_burst(filter, samples);            if (avg != m_lastAvg) {                m_lastAvg = avg;                emit meanUpdated(avg.mv);            }        }        signals:        void meanUpdated(std::int32_t milliVolts);        private:        MilliVolts m_lastAvg{0};    };        } // namespace hmi
  1. Defaulted C++20 operator<=> generates all 6 comparison operators with zero runtime overhead.
  2. virtual ~ITelemetryBackend() = default guarantees well-defined destruction via base unique_ptr.
cpp20-polymorphism(7) at a glance — GL-Q01
cpp20-polymorphism(7)       GL-Q01 Quick Reference       cpp20-polymorphism(7) NAME       virtual, override, final, concept, operator<=> - C++20 dispatch & value       contracts SYNOPSIS       struct Unit { int v; constexpr auto operator<=>(const Unit&) const noexcept = default; };       template <typename T> concept Sink = requires(T s, int x) { { s.push(x) } noexcept; };       class Base { public: virtual ~Base() = default; virtual void run() = 0; };       class Leaf final : public Base { public: void run() override; }; RULES       1. Any base class deleted via Base* MUST declare a public virtual       destructor. 2. Mark every overridden virtual method 'override' to catch       signature drift. 3. moc forbids class templates with Q_OBJECT, but       allows member function templates. Kernel Systems Academy            Lesson 1.3             cpp20-polymorphism(7) GL-Q01 quick reference · full manual page: man 7 cpp20-polymorphism 

Verifying vptr Footprint, Operator<=>, and Concept Dispatch in C++20

In verify.cpp, we prove four C++20 invariants quantitatively: (1) MilliVolts (sizeof == 4) supports constexpr + and <=> comparisons; (2) adding a virtual destructor grows PlainFilter by exactly sizeof(void *) bytes for the hidden vptr; (3) resetting a std::unique_ptr<ISink> runs both ~VirtualFilter() and ~ISink(); and (4) 31 CLOCK_MONOTONIC runs over 40,000 samples measure indirect ISink & dispatch versus SampleFilter concept dispatch.

Notice that correctness assertions check exact mathematical sums (50500 mV) and destructor counts (1/1) rather than fragile timing ratios, while volatile accumulation prevents dead-code elimination. Keep host x86_64 CLOCK_MONOTONIC numbers strictly scoped to host call overhead—never extrapolate them directly to ARMv7-A Cortex-A7 pipeline timing.

learner@ksa: ~/gl-q01/m01-l03
learner@ksa:~/gl-q01/m01-l03$ bat -H 15 -H 99 verify.cpp File: verify.cpp    #include <algorithm>    #include <array>    #include <cassert>    #include <compare>    #include <concepts>    #include <cstdint>    #include <cstdio>    #include <ctime>    #include <memory>        namespace hmi {        struct MilliVolts {        std::int32_t mv = 0;      constexpr auto operator<=>(const MilliVolts &) const noexcept = default;        constexpr MilliVolts operator+(MilliVolts r) const noexcept {            return MilliVolts{mv + r.mv};        }    };        struct PlainFilter {        std::int64_t sum_mv = 0;        std::int32_t count = 0;        void push(MilliVolts s) noexcept {            sum_mv += s.mv;            ++count;        }        MilliVolts total() const noexcept {            return MilliVolts{static_cast<std::int32_t>(sum_mv)};        }    };        class ISink {    public:        explicit ISink(int *base_dtors) noexcept : m_base_dtors(base_dtors) {}        virtual ~ISink() {            if (m_base_dtors) {                ++(*m_base_dtors);            }        }        virtual void push(MilliVolts s) noexcept = 0;        virtual MilliVolts total() const noexcept = 0;        private:        int *m_base_dtors;    };        class VirtualFilter final : public ISink {    public:        VirtualFilter(int *base_dtors, int *derived_dtors) noexcept            : ISink(base_dtors), m_derived_dtors(derived_dtors) {}        ~VirtualFilter() override {            if (m_derived_dtors) {                ++(*m_derived_dtors);            }        }        void push(MilliVolts s) noexcept override { m_sum += s.mv; }        MilliVolts total() const noexcept override {            return MilliVolts{static_cast<std::int32_t>(m_sum)};        }        private:        std::int64_t m_sum = 0;        int *m_derived_dtors;    };        template <typename F>    concept SampleFilter = requires(F f, const F cf, MilliVolts s) {        { f.push(s) } noexcept -> std::same_as<void>;        { cf.total() } noexcept -> std::same_as<MilliVolts>;    };        template <SampleFilter F>    static void run_concept(F &f, int n) noexcept {        for (int i = 1; i <= n; ++i) {            f.push(MilliVolts{i * 10});        }    }        static void run_virtual(ISink &s, int n) noexcept {        for (int i = 1; i <= n; ++i) {            s.push(MilliVolts{i * 10});        }    }        static std::uint64_t mono_ns() noexcept {        timespec ts{};        clock_gettime(CLOCK_MONOTONIC, &ts);        return static_cast<std::uint64_t>(ts.tv_sec) * 1000000000ULL +               static_cast<std::uint64_t>(ts.tv_nsec);    }        } // namespace hmi        int main() {        using hmi::MilliVolts;        static_assert(sizeof(MilliVolts) == 4);        static_assert((MilliVolts{1200} + MilliVolts{300}) == MilliVolts{1500});      static_assert(MilliVolts{900} < MilliVolts{1200});            struct Plain64 { std::int64_t x = 0; };        struct Poly64 { std::int64_t x = 0; virtual ~Poly64() = default; };        assert(sizeof(Poly64) == sizeof(Plain64) + sizeof(void *));            int base_dtors = 0, derived_dtors = 0;        {            std::unique_ptr<hmi::ISink> poly =                std::make_unique<hmi::VirtualFilter>(&base_dtors, &derived_dtors);            hmi::run_virtual(*poly, 100);            assert(poly->total() == MilliVolts{50500});        }        assert(derived_dtors == 1 && base_dtors == 1);            constexpr int kRuns = 31;        constexpr int kSamples = 40000;        std::array<std::uint64_t, kRuns> virt_ns{};        std::array<std::uint64_t, kRuns> conc_ns{};        volatile std::int64_t guard = 0;            for (int r = 0; r < kRuns; ++r) {            hmi::VirtualFilter vf(nullptr, nullptr);            hmi::ISink &iref = vf;            const std::uint64_t t0 = hmi::mono_ns();            hmi::run_virtual(iref, kSamples);            virt_ns[r] = hmi::mono_ns() - t0;            guard += iref.total().mv;                hmi::PlainFilter pf{};            const std::uint64_t t1 = hmi::mono_ns();            hmi::run_concept(pf, kSamples);            conc_ns[r] = hmi::mono_ns() - t1;            guard += pf.total().mv;        }        std::sort(virt_ns.begin(), virt_ns.end());        std::sort(conc_ns.begin(), conc_ns.end());        assert(guard != 0);            std::printf("sizeof_mv=%zu vptr=+%zub dtors=%d/%d virt_p50=%lluns conc_p50=%lluns\n",                    sizeof(MilliVolts), sizeof(Poly64) - sizeof(Plain64),                    derived_dtors, base_dtors,                    static_cast<unsigned long long>(virt_ns[kRuns / 2]),                    static_cast<unsigned long long>(conc_ns[kRuns / 2]));        return 0;    }
  1. Spaceship operator<=> and operator+ execute at compile time (verified by static_assert in main).
  2. Proves sizeof(Poly64) == sizeof(Plain64) + sizeof(void *) (+8B on LP64, +4B on ARMv7-A) and 1/1 polymorphic teardown.

Confirming vptr Size Growth and Polymorphic Teardown

Verify ./verify output: sizeof_mv=4 vptr=+8b dtors=1/1 on 64-bit Linux, followed by median virt_p50 and conc_p50 nanosecond measurements. static_assert proved MilliVolts relational and addition operators at compile time before main() even executed, and dtors=1/1 confirmed ~VirtualFilter() ran ahead of ~ISink() when std::unique_ptr<ISink> left scope.

Notice in strace that clock_gettime(CLOCK_MONOTONIC) resolves via the Linux kernel vDSO shared page without context-switching into Ring 0, leaving only write(1, ...) and exit_group(0) in the system-call trace.

learner@ksa: ~/gl-q01/m01-l03
learner@ksa:~/gl-q01/m01-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m01-l03./verifysizeof_mv=4 vptr=+8b dtors=1/1 virt_p50=85951ns conc_p50=85990nslearner@ksa:~/gl-q01/m01-l03
strace — learner@ksa: ~/gl-q01/m01-l03
learner@ksa:~/gl-q01/m01-l03strace -e trace=write,exit_group ./verifywrite(1, "sizeof_mv=4 vptr=+8b dtors=1/1 v"..., 66) = 66exit_group(0)                           = ?+++ exited with 0 +++

Polymorphic Slicing, Overload Hiding, and moc Template Limits

Module 1 has established your C++20 and QObject architectural foundation: isolated target CMake autogen graphs, deterministic move guards paired with heap-parented QObject trees, and virtual/override/final UI boundaries fed by constexpr value types and C++20 concept pipelines.

Now put all three lessons into practice in the lab_m01_cpp20_qobject_raii engineering studio below, where you will diagnose and repair a broken C++20 FdHandle, ObjectNode::reparent(), and DeleteQueue deferred sweep library against a 5-check TAP version 13 harness.

Silent Virtual Hiding When Omitting the override Specifier:

  • Symptom: Subclassing QWidget and writing void keyPressEvent(const QKeyEvent *e) (adding an extra const!) compiles with zero errors, yet pressing keys on the widget never invokes the handler.
  • Root Cause: QWidget::keyPressEvent(QKeyEvent *event) takes a non-const pointer; without override, C++ treats keyPressEvent(const QKeyEvent *) as a brand-new unrelated overload rather than overriding the vtable slot!
  • Fix: Append override to every virtual override in derived classes (void keyPressEvent(QKeyEvent *event) override;) so signature mismatches fail compilation immediately.

Placing Q_OBJECT Inside a C++ Class Template:

  • Symptom: Writing template <typename T> class SensorPlot : public QWidget { Q_OBJECT ... }; fails during the AUTOMOC step with Error: Template classes not supported by Q_OBJECT.
  • Root Cause: moc parses headers once before C++ template instantiation and cannot emit concrete staticMetaObject symbols for arbitrary future template arguments T.
  • Fix: Factor signals, slots, and Q_OBJECT into a non-templated base or presenter class (SensorPlotBase), or make only the non-signal ingestion helper a member function template (template <SampleFilter F> void ingest(F &)).

Guided Practice

Add a second SampleFilter-conforming struct ClampedFilter to verify.cpp that clamps each incoming MilliVolts sample into [MilliVolts{0}, MilliVolts{3300}] using <=> comparisons before accumulating, and verify run_concept(cf, 500) instantiates with zero changes to run_concept's template definition.

Independent Practice

Open labs/lab_m01_cpp20_qobject_raii/ and repair the three intentional ownership bugs in starter/core.cpp—self-move descriptor clobbering, ancestor-cycle reparent() corruption, and re-entrant DeleteQueue::flush() double deletion—until sh check.sh reports 5/5 TAP version 13 passes and ./files/lab_cli --bench records CLOCK_MONOTONIC percentiles.

Verification Checks

quiz · 1 of 3

Why does moc reject template <typename SampleT> class WaveformView : public QWidget { Q_OBJECT ... };?

quiz · 2 of 3

An abstract interface class ICanBus { public: ~ICanBus() = default; virtual bool send() = 0; }; is held via std::unique_ptr<ICanBus>. What defect occurs on scope exit?

quiz · 3 of 3

What compile-time and optimization benefit comes from declaring class AlarmBanner final : public QWidget and marking bool event(QEvent *e) override?

C++20 RAII Move Guards, Intrusive QObject Tree Cycles & deleteLater Sweep

env: host

1. Motivation

Production Qt 6 HMIs crash during dialog transitions when an RAII descriptor guard clobbers itself on self-move, dynamic widget reparenting introduces an ancestor cycle, or queuing deleteLater() on both a parent panel and its child button double-deletes the child on queue drain. In this studio you repair all three invariants in strict ISO C++20.

2. Learning objectives

  • Preserve single-close descriptor ownership across move construction and self-move assignment in hmi::FdHandle.
  • Enforce DAG acyclicity in ObjectNode::reparent() by walking is_ancestor_of(new_parent) before detaching the old parent.
  • Purge destroyed child pointers from DeleteQueue inside ObjectNode::~ObjectNode() so flush() never double-deletes.

3. Environment requirements

All automated verification steps run in unprivileged user space on a POSIX Linux host using g++ -std=c++20 -Wall -Wextra -Werror -pedantic and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).

4. Required software and hardware

  • Host workstation: g++ (-std=c++20 -Wall -Wextra -Werror -pedantic), GNU make, ar (binutils), and POSIX /bin/sh.
  • Target environment (optional hardware step, Section 13): ARMv7-A Cortex-A7 target running Linux kernel 6.12 LTS and Qt 6.8 eglfs or Wayland HMI panel to observe QObject::destroyed and QEvent::DeferredDelete ordering on real modal dialogs.

5. Complete executable commands

learner@ksa: ~/gl-q01/m01-l03
learner@ksa:~/gl-q01/m01-l03$ bat script.sh File: script.sh    make -B -C files    ./files/lab_cli    ./files/lab_cli --bench    sh check.sh

6. Annotated source code

files/core.cpp enforces the production invariants that starter/core.cpp breaks:

learner@ksa: ~/gl-q01/m01-l03
learner@ksa:~/gl-q01/m01-l03$ bat example.cpp File: example.cpp    FdHandle &FdHandle::operator=(FdHandle &&other) noexcept {        if (this != &other) {            reset();            m_fd = std::exchange(other.m_fd, -1);            m_closes = std::exchange(other.m_closes, nullptr);        }        return *this;    }    ...    ObjectNode::~ObjectNode() {        if (m_queue) {            m_queue->cancel(this); // prevents double-free if child was also queued!        }        while (!m_children.empty()) { ... }    }

starter/core.cpp contains three realistic C++20/Qt ownership bugs: (1) FdHandle::operator= omits if (this != &other) and closes an aliased handle prematurely; (2) ObjectNode::reparent() checks new_parent == this without checking is_ancestor_of(new_parent), creating infinite destructor cycles; and (3) ObjectNode::~ObjectNode() forgets m_queue->cancel(this), causing DeleteQueue::flush() to delete an already-freed child.

7. Expected output

Passing files/ run (sh check.sh, exit code 0):

learner@ksa: ~/gl-q01/m01-l03
learner@ksa:~/gl-q01/m01-l03$ bat listing.txt File: listing.txt    TAP version 13    1..5    ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic    ok 2 - archives core.o into libcore.a and links independent TAP verifier    ok 3 - enforces FdHandle self-move safety, early child unlink, and LIFO tree teardown    ok 4 - moves subtrees via reparent() while rejecting self or descendant cycles    ok 5 - cancels dying children from DeleteQueue during parent flush to prevent double-free    # pass 5/5

CLI verification output (./files/lab_cli):

learner@ksa: ~/gl-q01/m01-l03
learner@ksa:~/gl-q01/m01-l03$ bat listing.txt File: listing.txt    fd_closes=1 cycle_rejected=1 swept=1 destroyed=3

Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.

8. Explanation of observed behavior

With all three fixes restored in files/core.cpp, make -B -C files archives libcore.a cleanly under g++ -std=c++20 -Wall -Wextra -Werror -pedantic -O2, and sh check.sh passes all 5/5 TAP version 13 assertions including AddressSanitizer-equivalent double-free and cycle checks.

9. Experiment variations

  • Near transfer: Add a find_child(std::string_view name) recursive lookup method to ObjectNode matching QObject::findChild pre-order traversal and add a unit test verifying lookup after reparent().
  • Far transfer: Implement a WeakObjectPtr<ObjectNode> observer smart pointer (mirroring Qt's QPointer<T>) backed by a shared control flag cleared inside ~ObjectNode() so external caches detect deleted widgets in O(1).

10. Performance measurements

Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):

learner@ksa: ~/gl-q01/m01-l03
learner@ksa:~/gl-q01/m01-l03$ bat listing.txt File: listing.txt    BENCH lab_m01_cpp20_qobject_raii clock=CLOCK_MONOTONIC benchmark_samples=40 warmup=5 p50_ns=328 p95_ns=357 p99_ns=363 sink=72000

The CLOCK_MONOTONIC percentiles from ./files/lab_cli --bench measure host C++20 heap new/delete and vector unlink cost across a 3-node tree (p50 typically sub-microsecond). Never extrapolate host allocator latency to target ARMv7-A QWidget backing-store teardown or DRM framebuffer unmapping.

11. Troubleshooting

SymptomRoot causeFix
not ok 3 - enforces FdHandle self-move safety...FdHandle::operator= calls reset() unconditionally when this == &other.Wrap reset() and std::exchange assignments inside if (this != &other).
not ok 4 - moves subtrees via reparent()...reparent() permits attaching an ancestor underneath its own child or grandchild.Return false immediately when `new_parent == thisis_ancestor_of(new_parent)`.
not ok 5 - cancels dying children from DeleteQueue...DeleteQueue::flush() deletes panel (which deletes btn), then pops stale btn and deletes it again!Call if (m_queue) m_queue->cancel(this); at the top of ObjectNode::~ObjectNode().

12. Guided questions

  1. Why does ObjectNode::~ObjectNode() set child->m_parent = nullptr BEFORE executing delete child inside its while (!m_children.empty()) loop?
  • *Hint 1:* Trace what child->detach_from_parent() would do inside ~ObjectNode() if child->m_parent still pointed to the dying parent.
  • *Hint 2:* If child->m_parent remained non-null, delete child would call std::remove on the parent's m_children vector while the parent is already popping that exact vector, wasting O(N^2) scans and risking iterator invalidation.
  1. Why must ObjectNode::reparent() check is_ancestor_of(new_parent) BEFORE calling detach_from_parent()?
  • *Hint 1:* What state is this->parent() left in if detach_from_parent() runs first and the cycle check subsequently returns false?
  • *Hint 2:* Detaching before validating new_parent orphans this (m_parent == nullptr) when a rejected reparent() should be a strong no-op preserving the existing tree!

13. Independent challenges

Extend ObjectNode with a destroyed callback list (matching QObject::destroyed(QObject *)) that fires BEFORE base teardown completes, and verify that listeners observing a dying parent cannot see already-freed children in child_count().

14. Solutions and explanations

The reference files/core.cpp guards this != &other in FdHandle::operator=, validates new_parent == this || is_ancestor_of(new_parent) prior to mutating links in ObjectNode::reparent(), and cancels this from DeleteQueue at the start of ObjectNode::~ObjectNode().

Run locally in your terminal and check off each verification milestone.

Not started

Key takeaways

  • Declaring any virtual function adds one hidden vptr per instance pointing to a per-class vtable, whereas a C++20 concept constrains templates at compile time with zero indirect-branch overhead.
  • Deleting a derived object through a base-class pointer whose destructor is non-virtual invokes undefined behavior under ISO C++20; polymorphic interfaces must declare virtual ~Interface() = default;.
  • Marking virtual overrides with override catches base-signature drift at compile time, while marking leaf widgets final lets the optimizer devirtualize calls through leaf pointers.
  • Value structs such as fixed-point MilliVolts cleanly overload operator<=> and operator+, whereas Q_OBJECT classes forbid copy/value operators and cannot be C++ class templates because moc emits concrete QMetaObject globals.
Progress is saved on this device.
up next · module 1 labLab: C++20 RAII Move Guards, Intrusive QObject Tree Cycles & deleteLater Sweep (65 min)
→ module 1 lab

search — fzf

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

keyboard shortcuts — less

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

figure