Qt 6 Module Split, d_ptr PIMPL ABI & Implicitly Shared COW Buffers
Understand how Qt 6 separates headless and GUI modules, preserves shared-library ABI layout via d_ptr/q_ptr, and avoids hidden Copy-on-Write heap detaches across range-for loops.
What you'll learn
- Select minimal Qt 6 module dependencies so headless Linux telemetry daemons never link GUI raster or windowing libraries.
- Implement a binary-compatible
d_ptrandq_ptr(Private/Public) facade whosesizeofremains invariant when private fields grow. - Eliminate accidental Copy-on-Write heap allocations on
QStringandQByteArrayread paths usingstd::as_const(),constData(), andQStringView.
Binary Compatibility and Zero-Copy Value Passing in Qt 6
On an embedded root filesystem, linking a background CAN-bus logger against Qt6::Widgets drags libQt6Widgets.so.6, libQt6Gui.so.6, HarfBuzz font shaping, FreeType, and platform display plugins into RAM. Qt 6 enforces a strict layered split: QtCore provides non-GUI primitives (QObject, event loops, containers, I/O); QtGui adds window surfaces, fonts, QPainter, and the Rendering Hardware Interface (QRhi); and two sibling UI layers branch above QtGui—QtWidgets for deterministic control panels and QtQuick for GPU scene graphs.
Across every module, Qt solves two classic C++ library pain points. First, adding a private member variable to an ordinary C++ header class changes sizeof(Class) and breaks every already-compiled binary (fragile base class ABI); Qt hides all fields behind a single opaque d_ptr paired with a q_ptr back-link. Second, Qt value types (QString, QByteArray, QImage) use atomic Copy-on-Write (COW) implicit sharing—fast when read via const APIs, yet prone to silent heap copies when non-const iterators touch shared buffers!
Figure 2.1a. d_ptr freezes sizeof(PublicClass) across Qt 6 minor releases while atomic QArrayData refcounts defer buffer cloning until mutation.
mental model: Qt's d_ptr and implicit sharing work like a standardized shipping manifest (PublicClass) clipping onto a sealed cargo container (Private / QArrayData): customs scanners always read the exact same manifest card dimensions regardless of what racks change inside the box, and multiple departments share read-only tracking slips until someone breaks the seal to repack.
Where it stops working: Unlike physical shipping containers, QString and QByteArray are NOT thread-safe for concurrent mutation on the same C++ instance: only the internal QArrayData reference counter is atomic (std::memory_order_acq_rel), so two threads sharing distinct copies safely read/detach independently, whereas two threads mutating the SAME QString & variable still race on its 3-word header.
definition (PIMPL (d_ptr / q_ptr) and Implicit Sharing (COW)): PIMPL (Pointer to IMPLementation, standardized in Qt as the d-pointer pattern via Q_DECLARE_PRIVATE and Q_DECLARE_PUBLIC) moves all private state of Foo into FooPrivate accessed via d_ptr, while FooPrivate holds Foo *q_ptr to invoke public methods or emit signals on its owner. Implicit sharing (Copy-on-Write) pairs a 24-byte QArrayDataPointer<T> ({ QArrayData *d, T *ptr, qsizetype size } on 64-bit Qt 6) with an atomic reference count so copying QString (UTF-16LE char16_t) or QByteArray (char) is O(1) until mutated.
- Step 1. Forward-declare ClassPrivate in the public header and keep only d_ptr inside the public class layout.
- Step 2. Store a back-pointer q_ptr inside ClassPrivate whenever private helpers must notify the public QObject.
- Step 3. Use QString for localized human text (UTF-16LE) and QByteArray or std::span<const uint8_t> for binary frames.
- Step 4. Force const iteration with std::as_const(), cbegin(), or constData() on non-const local container copies.
Figure 2.1b. d_ptr stabilizes ABI sizeof; std::as_const() and constData() prevent silent COW detaches.
Inside Qt 6 QArrayDataPointer Layout and UTF-16LE vs Byte Storage
Qt 6 modernized QString, QByteArray, and QList<T> around a three-word QArrayDataPointer header (24 bytes on 64-bit, 12 bytes on 32-bit ARMv7-A): d points to the heap QArrayData control block (atomic<int> ref_, flags, alloc capacity), ptr points directly to the first element (enabling zero-offset slicing and Small String / literal views via QStringLiteral with d == nullptr!), and size holds the element count.
Pay close attention to element encoding! QString stores 16-bit UTF-16LE char16_t (QChar) code units (2 * size payload bytes), because ICU, HarfBuzz, and platform text APIs operate on UTF-16, whereas QByteArray stores raw 8-bit char bytes (1 * size payload bytes). In cow_pimpl_codec.cpp below, FrameCodec hides its CRC table seed inside FrameCodecPrivate (with q_ptr back-link) and hashes a by-value QByteArray via std::as_const(frame) so begin() resolves to const char * without detaching!
Figure 2.1b. Qt 6's 3-word QArrayDataPointer decouples control-block ownership (d) from payload start (ptr), powering zero-alloc QStringLiteral.
| Qt 6 Type | Code Unit / Ownership | Pass-by-Read Idiom | Hidden Detach / Lifetime Trap |
|---|---|---|---|
QString | 16-bit UTF-16LE (char16_t), COW QArrayData | QStringView (non-owning) or const QString & | for (QChar c : nonConstStr) detaches when ref > 1 |
QStringLiteral("...") | Compile-time .rodata UTF-16LE (d == nullptr) | Initialize QString constants with 0 heap cost | Mutating s[0] allocates first heap buffer on demand |
QByteArray | 8-bit char + trailing '\0', COW QArrayData | QByteArrayView or std::span<const char> via constData() | Calling buf.data() or buf[i] on non-const buf detaches |
QStringView / QByteArrayView | Non-owning { const T *ptr, qsizetype n } | Pass by value (16 B in 2 CPU registers on LP64) | Dangles if temporary backing QString dies before use! |
learner@ksa:~/gl-q01/m02-l01$ bat -H 34 -H 54 cow_pimpl_codec.cpp File: cow_pimpl_codec.cpp #include <QByteArray> #include <QString> #include <QtGlobal> #include <cstdint> #include <memory> #include <utility> namespace hmi { class FrameCodecPrivate; class FrameCodec { public: explicit FrameCodec(std::uint32_t seed); ~FrameCodec(); FrameCodec(const FrameCodec &) = delete; FrameCodec &operator=(const FrameCodec &) = delete; std::uint32_t seedMask() const noexcept; std::uint32_t crcFast(QByteArray frame) const noexcept; static std::size_t utf16ByteWidth(QString label) noexcept; private: Q_DECLARE_PRIVATE(FrameCodec) std::unique_ptr<FrameCodecPrivate> d_ptr; }; class FrameCodecPrivate { public: FrameCodecPrivate(FrameCodec *q, std::uint32_t s) noexcept : q_ptr(q), seed(s) {} std::uint32_t mixWithPublicMask(std::uint8_t byte) const noexcept { Q_Q(const FrameCodec); return (q->seedMask() ^ seed) + byte; } FrameCodec *const q_ptr; std::uint32_t seed; std::uint64_t decodedFrames = 0; // Growing Private preserves sizeof(FrameCodec)! Q_DECLARE_PUBLIC(FrameCodec) }; FrameCodec::FrameCodec(std::uint32_t seed) : d_ptr(std::make_unique<FrameCodecPrivate>(this, seed)) {} FrameCodec::~FrameCodec() = default; std::uint32_t FrameCodec::seedMask() const noexcept { return 0x5A5A0000U; } std::uint32_t FrameCodec::crcFast(QByteArray frame) const noexcept { Q_D(const FrameCodec); std::uint32_t acc = d->mixWithPublicMask(0U); for (char byte : std::as_const(frame)) { // Zero detach even when ref > 1! acc = (acc * 33U) ^ static_cast<std::uint8_t>(byte); } return acc; } std::size_t FrameCodec::utf16ByteWidth(QString label) noexcept { const char16_t *units = reinterpret_cast<const char16_t *>(label.constData()); (void)units; return static_cast<std::size_t>(label.size()) * sizeof(char16_t); } } // namespace hmi- Q_Q(const FrameCodec) dereferences q_ptr so FrameCodecPrivate can query public FrameCodec methods cleanly.
- std::as_const(frame) forces cbegin()/cend() so iterating a shared QByteArray copy never triggers detach().
QArrayData-PIMPL(3qt) GL-Q01 Quick Reference QArrayData-PIMPL(3qt) NAME Q_DECLARE_PRIVATE, Q_DECLARE_PUBLIC, QString, QByteArray - Qt 6 ABI & COW rules SYNOPSIS Q_DECLARE_PRIVATE(Class) // defines inline d_func() helper accessing d_ptr Q_DECLARE_PUBLIC(Class) // defines inline q_func() helper accessing q_ptr const char *QByteArray::constData() const noexcept; const QChar *QString::constData() const noexcept; RULES 1. Define ~PublicClass() out-of-line in .cpp after PublicClassPrivate is complete. 2. QString stores UTF-16LE (2 bytes per QChar); QByteArray stores 8-bit bytes. 3. Non-const data(), operator[], and begin() detach (deep-copy) whenever ref > 1. Use constData(), at(), cbegin(), or std::as_const() on read-only paths. Kernel Systems Academy Lesson 2.1 QArrayData-PIMPL(3qt) GL-Q01 quick reference · full manual page: man 3qt QArrayData-PIMPL Proving d_ptr ABI Invariance and Range-For COW Hazards in C++20
In verify.cpp, we construct both a bidirectional d_ptr/q_ptr PimplPanel facade and a generic CowArray<T> container instantiated for char (ByteBuf) and char16_t (Utf16Str, matching QString UTF-16LE width). A global g_heap_allocs counter tracks every control-block allocation across value copies, range-for loops, and rvalue moves.
Look closely at lines 88-100 in verify.cpp: iterating ByteBuf bad_loop = master; via for (char c : bad_loop) invokes non-const begin(), sees use_count() == 2, and increments g_heap_allocs even though the loop never writes to c! Wrapping std::as_const(good_loop) calls begin() const and performs zero heap allocations.
learner@ksa:~/gl-q01/m02-l01$ bat -H 65 -H 95 verify.cpp File: verify.cpp #include <atomic> #include <cassert> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstring> #include <memory> #include <utility> static int g_heap_allocs = 0; template <typename T> class CowArray { struct Block { std::atomic<int> ref{1}; std::size_t len = 0; T data[1]; }; static Block *alloc_block(const T *src, std::size_t n) { ++g_heap_allocs; auto *raw = new char[sizeof(Block) + n * sizeof(T)]; auto *b = new (raw) Block{}; b->len = n; for (std::size_t i = 0; i < n; ++i) { b->data[i] = src[i]; } b->data[n] = T{}; return b; } static void release(Block *b) noexcept { if (b && b->ref.fetch_sub(1, std::memory_order_acq_rel) == 1) { b->~Block(); delete[] reinterpret_cast<char *>(b); } } public: CowArray(const T *s, std::size_t n) : m_b(alloc_block(s, n)) {} ~CowArray() { release(m_b); } CowArray(const CowArray &o) noexcept : m_b(o.m_b) { if (m_b) { m_b->ref.fetch_add(1, std::memory_order_relaxed); } } CowArray(CowArray &&o) noexcept : m_b(std::exchange(o.m_b, nullptr)) {} CowArray &operator=(const CowArray &) = delete; int use_count() const noexcept { return m_b ? m_b->ref.load(std::memory_order_relaxed) : 0; } std::size_t size() const noexcept { return m_b ? m_b->len : 0; } const T *const_data() const noexcept { return m_b->data; } void detach() { if (m_b && m_b->ref.load(std::memory_order_acquire) > 1) { Block *fresh = alloc_block(m_b->data, m_b->len); release(m_b); m_b = fresh; } } T *begin() { detach(); return m_b->data; } T *end() { detach(); return m_b->data + m_b->len; } const T *begin() const noexcept { return m_b->data; } const T *end() const noexcept { return m_b->data + m_b->len; } private: Block *m_b = nullptr; }; class PanelFacade { struct Private { PanelFacade *const q_ptr; std::uint32_t scale = 10U; std::uint64_t extra_abi_fields[4]{}; std::uint32_t compute(std::uint32_t v) const noexcept { return q_ptr->base_offset() + v * scale; } }; public: PanelFacade() : d_ptr(std::make_unique<Private>(Private{this, 10U, {}})) {} ~PanelFacade() = default; std::uint32_t base_offset() const noexcept { return 100U; } std::uint32_t eval(std::uint32_t v) const noexcept { return d_ptr->compute(v); } private: std::unique_ptr<Private> d_ptr; }; int main() { static_assert(sizeof(PanelFacade) == sizeof(void *)); PanelFacade panel; assert(panel.eval(7) == 170U); g_heap_allocs = 0; CowArray<char> master("CAN_ID_204", 10); assert(g_heap_allocs == 1 && master.use_count() == 1); CowArray<char> good_loop(master); unsigned sum_good = 0; for (char c : std::as_const(good_loop)) { sum_good += static_cast<unsigned char>(c); } assert(g_heap_allocs == 1 && master.use_count() == 2); CowArray<char> bad_loop(master); unsigned sum_bad = 0; for (char c : bad_loop) { // Non-const range-for triggers detach()! sum_bad += static_cast<unsigned char>(c); } assert(sum_good == sum_bad && g_heap_allocs == 2 && bad_loop.use_count() == 1); const char16_t u16_lit[] = u"RPM"; CowArray<char16_t> qstr(u16_lit, 3); assert(qstr.size() * sizeof(char16_t) == 6); std::printf("PIMPL sizeof=%zub q_eval=%u allocs_after_const=1 " "allocs_after_nonconst=%d utf16_bytes=%zu\n", sizeof(PanelFacade), panel.eval(7), g_heap_allocs, qstr.size() * sizeof(char16_t)); return 0; }- Non-const begin() must call detach(), whereas begin() const returns m_b->data directly with zero allocation.
- static_assert proves PanelFacade occupies one pointer (8B on LP64) despite Private holding 48+ bytes.
Verifying PIMPL Footprint and COW Allocation Counts
Inspect ./verify output: PIMPL sizeof=8b q_eval=170 allocs_after_const=1 allocs_after_nonconst=2 utf16_bytes=6. Even though PanelFacade::Private carries a 32-byte extra_abi_fields array, sizeof(PanelFacade) stays locked at 8 bytes (sizeof(void *)), and q_ptr resolved base_offset() + 7 * 10 == 170 cleanly.
Meanwhile, std::as_const(good_loop) kept g_heap_allocs at 1, whereas omitting std::as_const on bad_loop silently doubled heap allocations (2) for the exact same read-only checksum!
learner@ksa:~/gl-q01/m02-l01g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m02-l01./verifyPIMPL sizeof=8b q_eval=170 allocs_after_const=1 allocs_after_nonconst=3 utf16_bytes=6learner@ksa:~/gl-q01/m02-l01learner@ksa:~/gl-q01/m02-l01strace -e trace=write,exit_group ./verifywrite(1, "PIMPL sizeof=8b q_eval=170 alloc"..., 86) = 86exit_group(0) = ?+++ exited with 0 +++Dangling Views, Incomplete-Type unique_ptr Destructors & False Detaches
Mastering d_ptr/q_ptr and implicit sharing explains why Qt 6 APIs pass QString and QByteArray cleanly across module boundaries without raw buffer ownership confusion—provided you pair read loops with std::as_const() / constData() and define PIMPL destructors out-of-line.
Next, Lesson 2.2 examines how Qt Designer .ui XML forms compile via uic into C++ setupUi() headers and why explicit PMF connect calls beat fragile connectSlotsByName naming conventions.
Inline Header Destructor on a Class Holding std::unique_ptr<FooPrivate>:
- Symptom: Writing
class Codec { ~Codec() {} ... std::unique_ptr<CodecPrivate> d_ptr; };incodec.hppfails compilation in client.cppfiles withinvalid application of 'sizeof' to incomplete type 'CodecPrivate'. - Root Cause:
std::default_delete<CodecPrivate>::operator()static-assertssizeof(CodecPrivate) > 0at the point where~Codec()is defined; incodec.hpp,CodecPrivateis only forward-declared! - Fix: Declare
~Codec();(without= defaultor{}) incodec.hpp, and placeCodec::~Codec() = default;insidecodec.cppbelow the full definition ofCodecPrivate.
Holding Raw constData() Pointers Across a Subsequent Non-Const Container Call:
- Symptom: Code obtains
const char *hdr = buf.constData();, then callsbuf[8] = 0x7E;whenbufwas shared (ref == 2), and later readshdr—observing stale or freed memory if the original owner also dropped its reference! - Root Cause:
buf[8] = 0x7Etriggersdetach(), allocating a brand-newQArrayDatabuffer forbufand decrementingrefon the blockhdrstill points into. - Fix: Re-acquire
constData()/ iterators AFTER all mutations finish, or calldetach()upfront before taking interior pointers.
Guided Practice
Add move-assignment and an edit_in_place(std::size_t idx, T val) method to CowArray<T> in verify.cpp, then pass std::move(bad_loop) into a sink function that mutates index 0. Confirm with assert(g_heap_allocs == 2) that mutating a moved buffer (use_count() == 1) modifies storage in place with zero heap allocations.
Independent Practice
Refactor a header-heavy sensor parser class into sensor_parser.hpp and sensor_parser.cpp using std::unique_ptr<SensorParserPrivate> d_ptr and SensorParser *const q_ptr. Add two new uint64_t counters to SensorParserPrivate and verify with nm / sizeof in a separate main.cpp that main.cpp.o's stack frame size for SensorParser never changes.
Verification Checks
Key takeaways
- Qt 6 splits
QtCore(non-GUI event/meta/IPC),QtGui(windows, fonts,QPainter, RHI), andQtWidgetsso headless daemons linkQt6::Corewithout pulling Wayland or X11 display dependencies. - Public Qt classes keep
sizeof(PublicClass)constant across minor library upgrades by storing internal fields in a*Privateheap struct accessed viad_ptr(Q_DECLARE_PRIVATE) with back-pointerq_ptr(Q_DECLARE_PUBLIC). QString(UTF-16LEchar16_tunits) andQByteArray(raw bytes) share one atomically reference-countedQArrayDatablock across copies until a mutating call triggersdetach()whenref > 1.- Iterating a shared non-const
QStringorQByteArraywithfor (auto ch : buf)invokes non-constbegin()and forces an unnecessary deep heap copy unless wrapped instd::as_const(buf)or read viaconstData().