RAII, Rule of Five & QObject Parent-Child Ownership Trees
Reconcile ISO C++20 RAII move semantics (std::unique_ptr and Rule of Five guards) with intrusive QObject parent-child trees so every handle and widget is freed once in exact order.
What you'll learn
- Implement a
noexceptRule-of-Five RAII guard innamespace hmiusingstd::exchangeand self-move protection for non-QObjectkernel handles. - Trace exact C++ destructor ordering across derived members, base
~QObject(), and intrusive child widget lists. - Eliminate heap corruption caused by stack-allocated child
QObjectordering errors or dualstd::unique_ptr+QObjectparenting.
Two Competing Lifetime Models Inside One C++20 Binary
Modern ISO C++20 centers memory safety on lexical (Resource Acquisition Is Initialization) and std::unique_ptr<T>: every heap object or POSIX file descriptor has a single owning variable whose destructor releases the resource deterministically when scope unwinds. Qt's QObject hierarchy predates C++11 move semantics and solves deep UI trees with an intrusive parent-child graph: passing this into new QLabel(tr("Ready"), this) appends the new child's this pointer into the parent's QObjectPrivate::children vector.
Collision occurs when engineers mix automatic stack lifetimes or std::unique_ptr with QObject parenting carelessly. C++ destroys local stack variables in strict reverse declaration order. If you write QLabel badge; QWidget panel; badge.setParent(&panel);, panel was constructed second and therefore unwinds FIRST—causing ~QWidget() to execute delete &badge on a stack address! Reconciling C++20 RAII with QObject trees requires one unambiguous ownership rule per allocation.
Figure 1.2a. Every QObject with a non-null parent must be heap-allocated; non-QObject descriptors belong in Rule-of-Five RAII guards.
mental model: A QObject parent works like a 19-inch industrial instrument rack: bolting heap-allocated modules (new QLabel(this)) into the rack means decommissioning the rack frame automatically disposes of every module still mounted inside, while unbolting and scrapping one module early cleanly empties its slot.
Where it stops working: Bolting a floor-welded transformer into a movable rack is physically impossible, whereas C++ happily lets you pass the address of a stack-allocated QLabel (&lbl) into QWidget* parenting APIs because QLabel* carries zero type-system distinction between stack and heap storage.
definition (RAII, , and Q_DISABLE_COPY_MOVE): Coined by Bjarne Stroustrup, RAII (Resource Acquisition Is Initialization) binds resource acquisition to a constructor and release to the matching destructor so stack unwinding leaks nothing even across early returns. When a low-level wrapper directly manages a raw handle like a POSIX descriptor, C++20's Rule of Five defines the destructor, deleted copy constructor/assignment, and noexcept move constructor/assignment. QObject invokes Q_DISABLE_COPY_MOVE(Class) to delete all four copy/move operations, enforcing stable address identity in parent-child trees.
- Step 1. Wrap POSIX file descriptors or buffers in a Rule-of-Five guard that neutralizes moved-from state to -1.
- Step 2. Allocate child widgets via new with this as parent, keeping non-owning raw pointers as class members.
- Step 3. Verify that derived member destructors never delete a child that base ~QObject() also owns.
- Step 4. Keep parentless root QObjects on main()'s stack or inside std::unique_ptr for deterministic shutdown.
Figure 1.2b. Use Rule-of-Five/unique_ptr for roots and OS handles; use heap + parent this for child QObjects.
Destructor Execution Sequence Across Derived Members and QObjectPrivate
Let us trace the exact ISO C++20 teardown sequence of hmi::AlarmBanner in panel_owner.cpp below. When AlarmBanner is destroyed, the compiler executes ~AlarmBanner()'s body first, then destroys non-static data members in reverse declaration order (m_ackBtn, m_status, m_buzzer), and ONLY THEN invokes base destructors ~QWidget() and ~QObject(). Because m_ackBtn and m_status are raw pointers, destroying those pointer variables does nothing; ~FdGuard() closes the buzzer descriptor once; and ~QObject() calls d->deleteChildren() to delete the heap QVBoxLayout, QLabel, and QPushButton.
Now imagine what happens if an engineer mistakenly declares std::unique_ptr<QLabel> m_status initialized with new QLabel(this)! During ~AlarmBanner(), ~unique_ptr() runs first and deletes the QLabel, whose ~QObject() detaches it from this. That looks lucky—until another child's destructor (or ~QWidget() focus cleanup) touches a sibling or layout expecting parent-driven teardown, or until a parent deletes the child first while unique_ptr still holds the raw address (double free!). Never split ownership of one allocation between two owners.
Figure 1.2b. Derived members unwind before ~QObject(), explaining why raw child pointers pair cleanly with parent-owned heap widgets.
| Resource Category | Correct C++20 / Qt 6 Owner | Pointer Type Stored | Why Alternatives Fail |
|---|---|---|---|
Child QWidget / QObject | Heap new T(..., this) (QObject parent) | Raw T * or QPointer<T> | std::unique_ptr<T> creates dual-owner double-delete risk |
Root QMainWindow / Headless Service | Stack variable in main() or std::unique_ptr<T> | Value or std::unique_ptr<T> | Raw new without parent leaks if an early return exits |
POSIX fd, mmap, or sqlite3 * | Rule-of-Five RAII guard or custom-deleter unique_ptr | By-value guard member (Rule of Zero) | QObject tree only deletes QObject * subclasses |
Modal Stack QDialog With Parent | Declared AFTER parent on stack (or heap WA_DeleteOnClose) | Local automatic QDialog dlg(&win) | Declaring dlg BEFORE win makes ~win() delete stack memory |
learner@ksa:~/gl-q01/m01-l02$ bat -H 19 -H 48 panel_owner.cpp File: panel_owner.cpp #include <QLabel> #include <QPushButton> #include <QVBoxLayout> #include <QWidget> #include <unistd.h> #include <utility> namespace hmi { class FdGuard { public: explicit FdGuard(int fd = -1) noexcept : m_fd(fd) {} ~FdGuard() { reset(); } FdGuard(const FdGuard &) = delete; FdGuard &operator=(const FdGuard &) = delete; FdGuard(FdGuard &&other) noexcept : m_fd(std::exchange(other.m_fd, -1)) {} FdGuard &operator=(FdGuard &&other) noexcept { if (this != &other) { reset(); m_fd = std::exchange(other.m_fd, -1); } return *this; } void reset(int fd = -1) noexcept { if (m_fd >= 0) { ::close(m_fd); } m_fd = fd; } int get() const noexcept { return m_fd; } private: int m_fd; }; class AlarmBanner final : public QWidget { Q_OBJECT public: explicit AlarmBanner(FdGuard buzzerFd, QWidget *parent = nullptr) : QWidget(parent), m_buzzer(std::move(buzzerFd)), m_status(new QLabel(tr("Nominal"), this)), m_ackBtn(new QPushButton(tr("Acknowledge"), this)) { auto *layout = new QVBoxLayout(this); layout->addWidget(m_status); layout->addWidget(m_ackBtn); } private: FdGuard m_buzzer; QLabel *m_status; QPushButton *m_ackBtn; }; } // namespace hmi- std::exchange(other.m_fd, -1) steals the descriptor atomically in C++ semantics and leaves other inert.
- Passing 'this' attaches QLabel and QPushButton to QObject's child tree while AlarmBanner follows Rule of Zero.
QObject-ownership(3qt) GL-Q01 Quick Reference QObject-ownership(3qt) NAME QObject, Q_DISABLE_COPY_MOVE - intrusive parent-child object tree lifetimes SYNOPSIS explicit QObject(QObject *parent = nullptr); virtual ~QObject(); const QObjectList &QObject::children() const; void QObject::setParent(QObject *parent); OWNERSHIP CONTRACT 1. Constructing QObject(parent) appends 'this' to parent's children() list. 2. ~QObject() deletes every remaining child in children(), then removes 'this' from its own parent (if still attached) and emits destroyed(QObject *). 3. Copy/move construction and assignment are deleted via Q_DISABLE_COPY_MOVE. HAZARDS Never parent a stack-allocated QObject onto a parent whose lifetime ends first. Kernel Systems Academy Lesson 1.2 QObject-ownership(3qt) GL-Q01 quick reference · full manual page: man 3qt QObject-ownership Proving RAII Move Semantics and Tree Unwinding in Host C++20
In verify.cpp, we build hmi::MoveHandle and an intrusive hmi::ObjectNode tree in strict ISO C++20 to verify four runtime invariants: (1) moving h1 into h2 and executing a self-move assignment closes the underlying descriptor exactly once; (2) deleting a heap child (early) ahead of its parent unlinks early cleanly; (3) destroying root sweeps remaining heap children in deterministic reverse order; and (4) parenting a stack node onto a shorter-lived stack parent triggers our explicit invalid-delete detector.
Study lines 47-56 of verify.cpp: popping child from m_children and setting child->m_parent = nullptr BEFORE delete child mirrors Qt's QObjectPrivate::deleteChildren() implementation so child destructors never scan or mutate a half-destroyed parent vector.
learner@ksa:~/gl-q01/m01-l02$ bat -H 22 -H 55 verify.cpp File: verify.cpp #include <algorithm> #include <cassert> #include <cstdio> #include <memory> #include <string> #include <utility> #include <vector> namespace hmi { class MoveHandle { public: MoveHandle(int fd, int *closes) noexcept : m_fd(fd), m_closes(closes) {} ~MoveHandle() { reset(); } MoveHandle(const MoveHandle &) = delete; MoveHandle &operator=(const MoveHandle &) = delete; MoveHandle(MoveHandle &&o) noexcept : m_fd(std::exchange(o.m_fd, -1)), m_closes(std::exchange(o.m_closes, nullptr)) {} MoveHandle &operator=(MoveHandle &&o) noexcept { if (this != &o) { reset(); m_fd = std::exchange(o.m_fd, -1); m_closes = std::exchange(o.m_closes, nullptr); } return *this; } void reset() noexcept { if (m_fd >= 0 && m_closes) { ++(*m_closes); } m_fd = -1; } private: int m_fd; int *m_closes; }; class ObjectNode { public: ObjectNode(std::string name, ObjectNode *parent, bool heap_allocated, std::vector<std::string> &log, int &stack_delete_faults) : m_name(std::move(name)), m_heap(heap_allocated), m_log(log), m_faults(stack_delete_faults) { set_parent(parent); } ObjectNode(const ObjectNode &) = delete; ObjectNode &operator=(const ObjectNode &) = delete; ~ObjectNode() { while (!m_children.empty()) { ObjectNode *child = m_children.back(); m_children.pop_back(); child->m_parent = nullptr; if (!child->m_heap) { ++m_faults; } else { delete child; } } if (m_parent) { auto &sibs = m_parent->m_children; sibs.erase(std::remove(sibs.begin(), sibs.end(), this), sibs.end()); } m_log.push_back(m_name); } void set_parent(ObjectNode *p) { if (m_parent == p || p == this) { return; } if (m_parent) { auto &old = m_parent->m_children; old.erase(std::remove(old.begin(), old.end(), this), old.end()); } m_parent = p; if (m_parent) { m_parent->m_children.push_back(this); } } private: std::string m_name; ObjectNode *m_parent = nullptr; bool m_heap; std::vector<ObjectNode *> m_children; std::vector<std::string> &m_log; int &m_faults; }; } // namespace hmi int main() { int closes = 0; { hmi::MoveHandle h1(9, &closes); hmi::MoveHandle h2(std::move(h1)); hmi::MoveHandle &alias = h2; h2 = std::move(alias); } assert(closes == 1); std::vector<std::string> log; int faults = 0; { auto root = std::make_unique<hmi::ObjectNode>("root", nullptr, true, log, faults); auto *early = new hmi::ObjectNode("early", root.get(), true, log, faults); new hmi::ObjectNode("label", root.get(), true, log, faults); new hmi::ObjectNode("btn", root.get(), true, log, faults); delete early; } assert(faults == 0); assert((log == std::vector<std::string>{"early", "btn", "label", "root"})); hmi::ObjectNode stack_child("stack_lbl", nullptr, false, log, faults); { hmi::ObjectNode shorter_parent("panel", nullptr, false, log, faults); stack_child.set_parent(&shorter_parent); } assert(faults == 1); std::printf("RAII closes=%d teardown=%s->%s->%s->%s stack_faults=%d\n", closes, log[0].c_str(), log[1].c_str(), log[2].c_str(), log[3].c_str(), faults); return 0; }- Guards self-move (this != &o) before calling reset() so moving an alias onto itself never closes a live handle.
- Detaches child->m_parent = nullptr before delete child; flags non-heap stack children instead of corrupting glibc heap.
Verifying Heap Teardown Order and Allocator System Calls
Check ./verify output: RAII closes=1 teardown=early->btn->label->root stack_faults=1. Explicitly deleting early logged its destruction immediately and detached it from root, leaving btn and label to be cleaned up in LIFO child order before root itself logged exit. Attaching stack_child to shorter_parent incremented stack_faults to 1 the instant shorter_parent's inner block exited.
Notice in strace how brk() establishes the C++ process heap arena once at startup, followed by all new/delete tree operations executing cleanly in user space without extra kernel syscalls before write(1, ...) and exit_group(0).
learner@ksa:~/gl-q01/m01-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m01-l02./verifyRAII closes=1 teardown=early->btn->label->root stack_faults=1learner@ksa:~/gl-q01/m01-l02learner@ksa:~/gl-q01/m01-l02strace -e trace=brk,write,exit_group ./verifybrk(NULL) = 0x6550aa822000brk(NULL) = 0x6550aa822000brk(0x6550aa843000) = 0x6550aa843000write(1, "RAII closes=1 teardown=early->bt"..., 62) = 62exit_group(0) = ?+++ exited with 0 +++Ownership Collisions in Production Qt 6 Codebases
Keep the ownership line razor-sharp in every code review: if an object inherits QObject and has a parent, allocate it with new and let the parent own it; if an object has no QObject parent—whether a root window or a Linux kernel device file descriptor—own it with a lexical stack scope, std::unique_ptr, or a Rule-of-Five guard.
Notice how Q_DISABLE_COPY_MOVE turns accidental value-copy bugs (void showPanel(QWidget w)) into immediate compile-time errors rather than silent object slicing. Next, Lesson 1.3 explores vptr/vtable polymorphism, operator overloads, and zero-overhead C++20 concept pipelines.
Calling delete this Directly Inside a Synchronous Slot Handler:
- Symptom: Clicking a 'Close Card'
QPushButtoninsideCardWidgettriggersdelete this;in the slot and crashes immediately insideQAbstractButton::mouseReleaseEventafter the slot returns. - Root Cause:
CardWidgetis the parent of theQPushButtoncurrently executing on the C++ call stack! Synchronousdelete thisdestroys the childQPushButtonwhileQPushButton's own member function is still active on the stack. - Fix: Call
this->deleteLater()instead ofdelete thisinside slots or event handlers so Qt posts aQEvent::DeferredDeleteticket processed safely after the active call stack unwinds.
Adding widget to a QLayout Without Realizing QLayout Reparents to the Host QWidget:
- Symptom: An engineer stores
std::unique_ptr<QPushButton> m_btn = std::make_unique<QPushButton>("Run");(initially parentless) and callslayout->addWidget(m_btn.get()), causing a double-free crash on window close. - Root Cause:
QLayout::addWidget()automatically callssetParent()to reparentm_btn.get()onto the layout's hostQWidget, silently creating dual ownership alongsidem_btn! - Fix: Allocate layout-managed widgets with
new QPushButton(tr("Run"), this)(or transfer ownership viam_btn.release()) and keep only a non-owningQPushButton *observer pointer.
Guided Practice
Modify verify.cpp to test the reverse stack declaration order: { ObjectNode parent("p", nullptr, false, log, faults); ObjectNode child("c", &parent, false, log, faults); }. Trace step-by-step why faults stays 0 in that exact block order (~child runs first and unlinks itself before ~parent runs), yet explain why coding guidelines still prefer heap allocation for child widgets when layouts reparent controls dynamically.
Independent Practice
Write a C++20 Rule-of-Five MmapRegion class wrapping a void * pointer and std::size_t byte length with std::exchange(other.m_addr, nullptr) move semantics, and embed it by value inside a Rule-of-Zero frame-buffer presenter class. Verify under -Wall -Wextra -Werror that copying the presenter is rejected at compile time while moving MmapRegion into its constructor compiles cleanly.
Verification Checks
Key takeaways
- Destroying a parent
QObjectwalksQObjectPrivate::childrenand callsdeleteon remaining children, so parenting a stack-allocated child onto a shorter-lived stack parent causes a fatal invalid-free crash. QObjectdeletes its copy constructor and copy-assignment operator (Q_DISABLE_COPY_MOVE) because tree identity,thisparent links, and live signal connections cannot be meaningfully cloned.- Deleting a heap-allocated child
QObjectbefore its parent executes~QObject(), which removesthisfrom the parent'schildrenlist immediately so the parent never double-deletes it later. - Production C++20 widgets follow the Rule of Zero by delegating POSIX descriptors to Rule-of-Five guards (
std::exchangemove transfer) while storingthis-parented child widgets as raw non-owning pointers.