Lab 1: C++20 RAII Move Guards, Intrusive QObject Tree Cycles & deleteLater Sweep
Enforce strict ISO C++20 compilation, target-scoped CMake AUTOMOC/AUTOUIC/AUTORCC code generation, deterministic RAII versus QObject parent-child lifetimes, and hybrid virtual-boundary plus C++20 concept polymorphism.
Prerequisites in this module
What ./check.sh verifies
- Builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic.
- Fix compiler warnings or errors in files/core.cpp.
- Archives core.o into libcore.a and links independent TAP verifier.
- Preserve public declarations in files/core.hpp so tests.cpp links.
step 1/15 · inspect starter files and specification
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.
learner@ksa:~/gl-q01/lab-m01ls -lastarter/Makefilestarter/cli.cppstarter/core.cppstarter/core.hpplearner@ksa:~/gl-q01/lab-m01starter: starter/Makefile
learner@ksa:~/gl-q01/lab-m01$ bat starter/Makefile File: starter/Makefile CC_BIN = g++ AR = ar CFLAGS_ALL = -std=c++20 -Wall -Wextra -Werror -pedantic -O2 LDLIBS = all: libcore.a lab_cli libcore.a: core.o $(AR) rcs $@ $^ lab_cli: cli.o libcore.a $(CC_BIN) $(CFLAGS_ALL) cli.o libcore.a $(LDLIBS) -o $@ %.o: %.cpp core.hpp $(CC_BIN) $(CFLAGS_ALL) -c $< -o $@ .PHONY: all clean clean: rm -f core.o cli.o libcore.a lab_clistarter: starter/cli.cpp
learner@ksa:~/gl-q01/lab-m01$ bat starter/cli.cpp File: starter/cli.cpp #include "core.hpp" #include <algorithm> #include <array> #include <cstdint> #include <cstdio> #include <cstring> #include <ctime> #include <memory> #include <string> #include <utility> #include <vector> static std::uint64_t now_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); } static int run_bench() { constexpr int kWarmup = 5; constexpr int kSamples = 40; constexpr int kInner = 200; std::array<std::uint64_t, kSamples> ns{}; volatile std::size_t sink = 0; for (int w = 0; w < kWarmup + kSamples; ++w) { const std::uint64_t t0 = now_ns(); for (int i = 0; i < kInner; ++i) { int closes = 0; { hmi::FdHandle h1(3, &closes); hmi::FdHandle h2(std::move(h1)); sink += static_cast<std::size_t>(h2.get()); } std::vector<std::string> log; hmi::DeleteQueue q; auto *root = new hmi::ObjectNode("root", nullptr, log, &q); auto *mid = new hmi::ObjectNode("mid", root, log, &q); new hmi::ObjectNode("leaf", mid, log, &q); root->delete_later(); mid->delete_later(); sink += q.flush() + static_cast<std::size_t>(closes) + log.size(); } const std::uint64_t dt = (now_ns() - t0) / static_cast<std::uint64_t>(kInner); if (w >= kWarmup) { ns[static_cast<std::size_t>(w - kWarmup)] = dt; } } std::sort(ns.begin(), ns.end()); std::printf("BENCH lab_m01_cpp20_qobject_raii clock=CLOCK_MONOTONIC " "benchmark_samples=40 warmup=5 p50_ns=%llu p95_ns=%llu p99_ns=%llu sink=%zu\n", static_cast<unsigned long long>(ns[20]), static_cast<unsigned long long>(ns[38]), static_cast<unsigned long long>(ns[39]), static_cast<std::size_t>(sink)); return 0; } int main(int argc, char **argv) { if (argc > 1 && std::strcmp(argv[1], "--bench") == 0) { return run_bench(); } int closes = 0; { hmi::FdHandle a(5, &closes); hmi::FdHandle b(std::move(a)); hmi::FdHandle &self = b; b = std::move(self); } std::vector<std::string> log; hmi::DeleteQueue q; auto *win = new hmi::ObjectNode("win", nullptr, log, &q); auto *panel = new hmi::ObjectNode("panel", win, log, &q); auto *btn = new hmi::ObjectNode("btn", panel, log, &q); const bool cycle_rejected = !win->reparent(btn); win->delete_later(); btn->delete_later(); const std::size_t swept = q.flush(); std::printf("fd_closes=%d cycle_rejected=%d swept=%zu destroyed=%zu\n", closes, cycle_rejected ? 1 : 0, swept, log.size()); return (closes == 1 && cycle_rejected && swept == 1 && log.size() == 3) ? 0 : 1; }starter: starter/core.cpp
learner@ksa:~/gl-q01/lab-m01$ bat starter/core.cpp File: starter/core.cpp #include "core.hpp" #include <algorithm> #include <utility> namespace hmi { FdHandle::FdHandle(int fd, int *close_counter) noexcept : m_fd(fd), m_closes(close_counter) {} FdHandle::~FdHandle() { reset(); } FdHandle::FdHandle(FdHandle &&other) noexcept : m_fd(std::exchange(other.m_fd, -1)), m_closes(std::exchange(other.m_closes, nullptr)) {} FdHandle &FdHandle::operator=(FdHandle &&other) noexcept { reset(); /* BUG: unguarded self-move closes live descriptor */ m_fd = std::exchange(other.m_fd, -1); m_closes = std::exchange(other.m_closes, nullptr); return *this; } void FdHandle::reset() noexcept { if (m_fd >= 0 && m_closes) { ++(*m_closes); } m_fd = -1; } ObjectNode::ObjectNode(std::string name, ObjectNode *parent, std::vector<std::string> &destroy_log, DeleteQueue *queue) : m_name(std::move(name)), m_log(destroy_log), m_queue(queue) { if (parent && parent != this) { m_parent = parent; m_parent->m_children.push_back(this); } } ObjectNode::~ObjectNode() { /* BUG: omits m_queue->cancel(this), leaving dangling child pointer in DeleteQueue */ while (!m_children.empty()) { ObjectNode *child = m_children.back(); m_children.pop_back(); child->m_parent = nullptr; delete child; } detach_from_parent(); m_log.push_back(m_name); } bool ObjectNode::is_ancestor_of(const ObjectNode *candidate) const noexcept { for (const ObjectNode *cur = candidate; cur != nullptr; cur = cur->m_parent) { if (cur == this) { return true; } } return false; } void ObjectNode::detach_from_parent() noexcept { if (!m_parent) { return; } auto &sibs = m_parent->m_children; sibs.erase(std::remove(sibs.begin(), sibs.end(), this), sibs.end()); m_parent = nullptr; } bool ObjectNode::reparent(ObjectNode *new_parent) { if (new_parent == this) { /* BUG: fails to reject reparenting onto own descendant */ return false; } if (m_parent == new_parent) { return true; } detach_from_parent(); m_parent = new_parent; if (m_parent) { m_parent->m_children.push_back(this); } return true; } void ObjectNode::delete_later() { if (m_queue) { m_queue->schedule(this); } } void DeleteQueue::schedule(ObjectNode *node) { if (!node) { return; } if (std::find(m_pending.begin(), m_pending.end(), node) == m_pending.end()) { m_pending.push_back(node); } } void DeleteQueue::cancel(ObjectNode *node) noexcept { m_pending.erase(std::remove(m_pending.begin(), m_pending.end(), node), m_pending.end()); } std::size_t DeleteQueue::flush() { std::size_t swept = 0; while (!m_pending.empty()) { ObjectNode *next = m_pending.front(); m_pending.erase(m_pending.begin()); delete next; ++swept; } return swept; } } // namespace hmistarter: starter/core.hpp
learner@ksa:~/gl-q01/lab-m01$ bat starter/core.hpp File: starter/core.hpp #pragma once #include <compare> #include <cstddef> #include <cstdint> #include <string> #include <vector> 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}; } }; class FdHandle { public: FdHandle(int fd, int *close_counter) noexcept; ~FdHandle(); FdHandle(const FdHandle &) = delete; FdHandle &operator=(const FdHandle &) = delete; FdHandle(FdHandle &&other) noexcept; FdHandle &operator=(FdHandle &&other) noexcept; void reset() noexcept; int get() const noexcept { return m_fd; } private: int m_fd = -1; int *m_closes = nullptr; }; class DeleteQueue; class ObjectNode { public: ObjectNode(std::string name, ObjectNode *parent, std::vector<std::string> &destroy_log, DeleteQueue *queue = nullptr); ObjectNode(const ObjectNode &) = delete; ObjectNode &operator=(const ObjectNode &) = delete; virtual ~ObjectNode(); const std::string &name() const noexcept { return m_name; } ObjectNode *parent() const noexcept { return m_parent; } std::size_t child_count() const noexcept { return m_children.size(); } bool reparent(ObjectNode *new_parent); void delete_later(); private: bool is_ancestor_of(const ObjectNode *candidate) const noexcept; void detach_from_parent() noexcept; std::string m_name; ObjectNode *m_parent = nullptr; std::vector<ObjectNode *> m_children; std::vector<std::string> &m_log; DeleteQueue *m_queue = nullptr; }; class DeleteQueue { public: void schedule(ObjectNode *node); void cancel(ObjectNode *node) noexcept; std::size_t flush(); std::size_t pending() const noexcept { return m_pending.size(); } private: std::vector<ObjectNode *> m_pending; }; } // namespace hmistep 2/15 · 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 walkingis_ancestor_of(new_parent)before detaching the old parent. - Purge destroyed child pointers from
DeleteQueueinsideObjectNode::~ObjectNode()soflush()never double-deletes.
step 3/15 · 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).
step 4/15 · 4. required software and hardware
- Host workstation:
g++(-std=c++20 -Wall -Wextra -Werror -pedantic), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
ARMv7-ACortex-A7target runningLinux kernel6.12 LTS and Qt 6.8eglfsor Wayland HMI panel to observeQObject::destroyedandQEvent::DeferredDeleteordering on real modal dialogs.
step 5/15 · 5. complete executable commands
learner@ksa:~/gl-q01/lab-m01$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.shstep 6/15 · 6. annotated source code
files/core.cpp enforces the production invariants that starter/core.cpp breaks:
learner@ksa:~/gl-q01/lab-m01$ 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.
step 7/15 · 7. expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-q01/lab-m01$ 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/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-q01/lab-m01$ bat listing.txt File: listing.txt fd_closes=1 cycle_rejected=1 swept=1 destroyed=3Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
step 8/15 · 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.
step 9/15 · 9. experiment variations
- Near transfer: Add a
find_child(std::string_view name)recursive lookup method toObjectNodematchingQObject::findChildpre-order traversal and add a unit test verifying lookup afterreparent(). - Far transfer: Implement a
WeakObjectPtr<ObjectNode>observer smart pointer (mirroring Qt'sQPointer<T>) backed by a shared control flag cleared inside~ObjectNode()so external caches detect deleted widgets inO(1).
step 10/15 · 10. performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-q01/lab-m01$ 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=72000The 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.
step 11/15 · 11. troubleshooting
| Symptom | Root cause | Fix | ||
|---|---|---|---|---|
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 == this | is_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(). |
step 12/15 · 12. guided questions
- Why does
ObjectNode::~ObjectNode()setchild->m_parent = nullptrBEFORE executingdelete childinside itswhile (!m_children.empty())loop?
- *Hint 1:* Trace what
child->detach_from_parent()would do inside~ObjectNode()ifchild->m_parentstill pointed to the dying parent. - *Hint 2:* If
child->m_parentremained non-null,delete childwould callstd::removeon the parent'sm_childrenvector while the parent is already popping that exact vector, wastingO(N^2)scans and risking iterator invalidation.
- Why must
ObjectNode::reparent()checkis_ancestor_of(new_parent)BEFORE callingdetach_from_parent()?
- *Hint 1:* What state is
this->parent()left in ifdetach_from_parent()runs first and the cycle check subsequently returnsfalse? - *Hint 2:* Detaching before validating
new_parentorphansthis(m_parent == nullptr) when a rejectedreparent()should be a strong no-op preserving the existing tree!
step 13/15 · 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().
step 14/15 · 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().
step 15/15 · run verification and inspect output
Run the verification command and confirm the output matches the expected contract.
learner@ksa:~/gl-q01/lab-m01./files/lab_clilearner@ksa:~/gl-q01/lab-m01fd_closes=1 cycle_rejected=1 swept=1 destroyed=3Progressive hints & solution
hint 1
Compare starter/Makefile against the module lessons. Focus first on: Builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic.
hint 2
Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.
solution
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/Makefile
learner@ksa:~/gl-q01/lab-m01$ bat files/Makefile File: files/Makefile CC_BIN = g++ AR = ar CFLAGS_ALL = -std=c++20 -Wall -Wextra -Werror -pedantic -O2 LDLIBS = all: libcore.a lab_cli libcore.a: core.o $(AR) rcs $@ $^ lab_cli: cli.o libcore.a $(CC_BIN) $(CFLAGS_ALL) cli.o libcore.a $(LDLIBS) -o $@ %.o: %.cpp core.hpp $(CC_BIN) $(CFLAGS_ALL) -c $< -o $@ .PHONY: all clean clean: rm -f core.o cli.o libcore.a lab_clisolution: files/cli.cpp
learner@ksa:~/gl-q01/lab-m01$ bat files/cli.cpp File: files/cli.cpp #include "core.hpp" #include <algorithm> #include <array> #include <cstdint> #include <cstdio> #include <cstring> #include <ctime> #include <memory> #include <string> #include <utility> #include <vector> static std::uint64_t now_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); } static int run_bench() { constexpr int kWarmup = 5; constexpr int kSamples = 40; constexpr int kInner = 200; std::array<std::uint64_t, kSamples> ns{}; volatile std::size_t sink = 0; for (int w = 0; w < kWarmup + kSamples; ++w) { const std::uint64_t t0 = now_ns(); for (int i = 0; i < kInner; ++i) { int closes = 0; { hmi::FdHandle h1(3, &closes); hmi::FdHandle h2(std::move(h1)); sink += static_cast<std::size_t>(h2.get()); } std::vector<std::string> log; hmi::DeleteQueue q; auto *root = new hmi::ObjectNode("root", nullptr, log, &q); auto *mid = new hmi::ObjectNode("mid", root, log, &q); new hmi::ObjectNode("leaf", mid, log, &q); root->delete_later(); mid->delete_later(); sink += q.flush() + static_cast<std::size_t>(closes) + log.size(); } const std::uint64_t dt = (now_ns() - t0) / static_cast<std::uint64_t>(kInner); if (w >= kWarmup) { ns[static_cast<std::size_t>(w - kWarmup)] = dt; } } std::sort(ns.begin(), ns.end()); std::printf("BENCH lab_m01_cpp20_qobject_raii clock=CLOCK_MONOTONIC " "benchmark_samples=40 warmup=5 p50_ns=%llu p95_ns=%llu p99_ns=%llu sink=%zu\n", static_cast<unsigned long long>(ns[20]), static_cast<unsigned long long>(ns[38]), static_cast<unsigned long long>(ns[39]), static_cast<std::size_t>(sink)); return 0; } int main(int argc, char **argv) { if (argc > 1 && std::strcmp(argv[1], "--bench") == 0) { return run_bench(); } int closes = 0; { hmi::FdHandle a(5, &closes); hmi::FdHandle b(std::move(a)); hmi::FdHandle &self = b; b = std::move(self); } std::vector<std::string> log; hmi::DeleteQueue q; auto *win = new hmi::ObjectNode("win", nullptr, log, &q); auto *panel = new hmi::ObjectNode("panel", win, log, &q); auto *btn = new hmi::ObjectNode("btn", panel, log, &q); const bool cycle_rejected = !win->reparent(btn); win->delete_later(); btn->delete_later(); const std::size_t swept = q.flush(); std::printf("fd_closes=%d cycle_rejected=%d swept=%zu destroyed=%zu\n", closes, cycle_rejected ? 1 : 0, swept, log.size()); return (closes == 1 && cycle_rejected && swept == 1 && log.size() == 3) ? 0 : 1; }solution: files/core.cpp
learner@ksa:~/gl-q01/lab-m01$ bat files/core.cpp File: files/core.cpp #include "core.hpp" #include <algorithm> #include <utility> namespace hmi { FdHandle::FdHandle(int fd, int *close_counter) noexcept : m_fd(fd), m_closes(close_counter) {} FdHandle::~FdHandle() { reset(); } FdHandle::FdHandle(FdHandle &&other) noexcept : m_fd(std::exchange(other.m_fd, -1)), m_closes(std::exchange(other.m_closes, nullptr)) {} 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; } void FdHandle::reset() noexcept { if (m_fd >= 0 && m_closes) { ++(*m_closes); } m_fd = -1; } ObjectNode::ObjectNode(std::string name, ObjectNode *parent, std::vector<std::string> &destroy_log, DeleteQueue *queue) : m_name(std::move(name)), m_log(destroy_log), m_queue(queue) { if (parent && parent != this) { m_parent = parent; m_parent->m_children.push_back(this); } } ObjectNode::~ObjectNode() { if (m_queue) { m_queue->cancel(this); } while (!m_children.empty()) { ObjectNode *child = m_children.back(); m_children.pop_back(); child->m_parent = nullptr; delete child; } detach_from_parent(); m_log.push_back(m_name); } bool ObjectNode::is_ancestor_of(const ObjectNode *candidate) const noexcept { for (const ObjectNode *cur = candidate; cur != nullptr; cur = cur->m_parent) { if (cur == this) { return true; } } return false; } void ObjectNode::detach_from_parent() noexcept { if (!m_parent) { return; } auto &sibs = m_parent->m_children; sibs.erase(std::remove(sibs.begin(), sibs.end(), this), sibs.end()); m_parent = nullptr; } bool ObjectNode::reparent(ObjectNode *new_parent) { if (new_parent == this || is_ancestor_of(new_parent)) { return false; } if (m_parent == new_parent) { return true; } detach_from_parent(); m_parent = new_parent; if (m_parent) { m_parent->m_children.push_back(this); } return true; } void ObjectNode::delete_later() { if (m_queue) { m_queue->schedule(this); } } void DeleteQueue::schedule(ObjectNode *node) { if (!node) { return; } if (std::find(m_pending.begin(), m_pending.end(), node) == m_pending.end()) { m_pending.push_back(node); } } void DeleteQueue::cancel(ObjectNode *node) noexcept { m_pending.erase(std::remove(m_pending.begin(), m_pending.end(), node), m_pending.end()); } std::size_t DeleteQueue::flush() { std::size_t swept = 0; while (!m_pending.empty()) { ObjectNode *next = m_pending.front(); m_pending.erase(m_pending.begin()); delete next; ++swept; } return swept; } } // namespace hmisolution: files/core.hpp
learner@ksa:~/gl-q01/lab-m01$ bat files/core.hpp File: files/core.hpp #pragma once #include <compare> #include <cstddef> #include <cstdint> #include <string> #include <vector> 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}; } }; class FdHandle { public: FdHandle(int fd, int *close_counter) noexcept; ~FdHandle(); FdHandle(const FdHandle &) = delete; FdHandle &operator=(const FdHandle &) = delete; FdHandle(FdHandle &&other) noexcept; FdHandle &operator=(FdHandle &&other) noexcept; void reset() noexcept; int get() const noexcept { return m_fd; } private: int m_fd = -1; int *m_closes = nullptr; }; class DeleteQueue; class ObjectNode { public: ObjectNode(std::string name, ObjectNode *parent, std::vector<std::string> &destroy_log, DeleteQueue *queue = nullptr); ObjectNode(const ObjectNode &) = delete; ObjectNode &operator=(const ObjectNode &) = delete; virtual ~ObjectNode(); const std::string &name() const noexcept { return m_name; } ObjectNode *parent() const noexcept { return m_parent; } std::size_t child_count() const noexcept { return m_children.size(); } bool reparent(ObjectNode *new_parent); void delete_later(); private: bool is_ancestor_of(const ObjectNode *candidate) const noexcept; void detach_from_parent() noexcept; std::string m_name; ObjectNode *m_parent = nullptr; std::vector<ObjectNode *> m_children; std::vector<std::string> &m_log; DeleteQueue *m_queue = nullptr; }; class DeleteQueue { public: void schedule(ObjectNode *node); void cancel(ObjectNode *node) noexcept; std::size_t flush(); std::size_t pending() const noexcept { return m_pending.size(); } private: std::vector<ObjectNode *> m_pending; }; } // namespace hmiRun the check
From labs/lab_m01_cpp20_qobject_raii/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-q01/lab-m01./check.shTAP version 131..5ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedanticok 2 - archives core.o into libcore.a and links independent TAP verifierok 3 - enforces FdHandle self-move safety, early child unlink, and LIFO tree teardownok 4 - moves subtrees via reparent() while rejecting self or descendant cyclesok 5 - cancels dying children from DeleteQueue during parent flush to prevent double-free# pass 5/5On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
learner@ksa:~/gl-q01/lab-m01./check.shTAP version 131..5ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedanticok 2 - archives core.o into libcore.a and links independent TAP verifiernot ok 3 - enforces FdHandle self-move safety, early child unlink, and LIFO tree teardownFAIL: guard if (this != &other) in FdHandle::operator= before calling reset() and pop children in reverse order --- message: 'got self-move clobbered handle: h2=-1 closes=1' hint: 'guard if (this != &other) in FdHandle::operator= before calling reset() and pop children in reverse order' ...not ok 4 - moves subtrees via reparent() while rejecting self or descendant cyclesFAIL: reject new_parent == this || is_ancestor_of(new_parent) in ObjectNode::reparent without detaching current parent --- message: 'got build_failed' hint: 'reject new_parent == this || is_ancestor_of(new_parent) in ObjectNode::reparent without detaching current parent' ...not ok 5 - cancels dying children from DeleteQueue during parent flush to prevent double-freeFAIL: call m_queue->cancel(this) inside ObjectNode::~ObjectNode() so swept children are purged from m_pending --- message: 'got build_failed' hint: 'call m_queue->cancel(this) inside ObjectNode::~ObjectNode() so swept children are purged from m_pending' ...# pass 2/5Segmentation faultSegmentation faultnote: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....
inspect harness: check.sh
learner@ksa:~/gl-q01/lab-m01$ bat check.sh File: check.sh #!/bin/sh set -u cd "$(dirname "$0")" || exit 1 PASS=0 WORK=$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab.XXXXXX") || exit 1 trap 'rm -rf "$WORK"' EXIT HUP INT TERM cp -R files "$WORK/files" printf 'TAP version 13\n1..5\n' if make -B -C "$WORK/files" >"$WORK/build.log" 2>&1; then printf 'ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic\n' PASS=$((PASS + 1)) else printf 'not ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic\n' printf 'FAIL: fix compiler warnings or errors in files/core.cpp\n' fi if [ -f "$WORK/files/libcore.a" ] && g++ -std=c++20 -Wall -Wextra -Werror -pedantic -O2 -I"$WORK/files" tests.cpp "$WORK/files/libcore.a" -o "$WORK/verify" >>"$WORK/build.log" 2>&1; then printf 'ok 2 - archives core.o into libcore.a and links independent TAP verifier\n' PASS=$((PASS + 1)) else printf 'not ok 2 - archives core.o into libcore.a and links independent TAP verifier\n' printf 'FAIL: preserve public declarations in files/core.hpp so tests.cpp links\n' fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 1 2>&1); then printf 'ok 3 - enforces FdHandle self-move safety, early child unlink, and LIFO tree teardown\n' PASS=$((PASS + 1)) else printf 'not ok 3 - enforces FdHandle self-move safety, early child unlink, and LIFO tree teardown\n' printf 'FAIL: guard if (this != &other) in FdHandle::operator= before calling reset() and pop children in reverse order\n' printf " ---\n message: 'got %s'\n hint: 'guard if (this != &other) in FdHandle::operator= before calling reset() and pop children in reverse order'\n ...\n" "${OUT:-build_failed}" fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 2 2>&1); then printf 'ok 4 - moves subtrees via reparent() while rejecting self or descendant cycles\n' PASS=$((PASS + 1)) else printf 'not ok 4 - moves subtrees via reparent() while rejecting self or descendant cycles\n' printf 'FAIL: reject new_parent == this || is_ancestor_of(new_parent) in ObjectNode::reparent without detaching current parent\n' printf " ---\n message: 'got %s'\n hint: 'reject new_parent == this || is_ancestor_of(new_parent) in ObjectNode::reparent without detaching current parent'\n ...\n" "${OUT:-build_failed}" fi if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 3 2>&1); then printf 'ok 5 - cancels dying children from DeleteQueue during parent flush to prevent double-free\n' PASS=$((PASS + 1)) else printf 'not ok 5 - cancels dying children from DeleteQueue during parent flush to prevent double-free\n' printf 'FAIL: call m_queue->cancel(this) inside ObjectNode::~ObjectNode() so swept children are purged from m_pending\n' printf " ---\n message: 'got %s'\n hint: 'call m_queue->cancel(this) inside ObjectNode::~ObjectNode() so swept children are purged from m_pending'\n ...\n" "${OUT:-build_failed}" fi printf '# pass %d/5\n' "$PASS" [ "$PASS" -eq 5 ]Definition of done
Verification checklist
status: 0/3 checks verified
Troubleshooting
Compiler fails under -Werror on sign conversion or unused args
Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.
./check.sh reports missing files in files/
Invoke ./check.sh from inside labs/lab_m01_cpp20_qobject_raii/ so relative paths to files/ resolve directly.