Trusted Software Excellence across Desktop and Embedded
Take a glance at the areas of expertise where KDAB excels ranging from swift troubleshooting, ongoing consulting and training to multi-year, large-scale software development projects.
Find out why customers from innovative industries rely on our extensive expertise, including Medical, Biotech, Science, Renewable Energy, Transportation, Mobility, Aviation, Automation, Electronics, Agriculture and Defense.
High-quality Embedded Engineering across the Stack
To successfully develop an embedded device that meets your expectations regarding quality, budget and time to market, all parts of the project need to fit perfectly together.
Learn more about KDAB's expertise in embedded software development.
Where the capabilities of modern mobile devices or web browsers fall short, KDAB engineers help you expertly architect and build high-functioning desktop and workstation applications.
Extensible, Safety-compliant Software for the Medical Sector
Create intelligent, patient-focused medical software and devices and stay ahead with technology that adapts to your needs.
KDAB offers you expertise in developing a broad spectrum of clinical and home-healthcare devices, including but not limited to, internal imaging systems, robotic surgery devices, ventilators and non-invasive monitoring systems.
Building digital dashboards and cockpits with fluid animations and gesture-controlled touchscreens is a big challenge.
In over two decades of developing intricate UI solutions for cars, trucks, tractors, scooters, ships, airplanes and more, the KDAB team has gained market leading expertise in this realm.
Build on Advanced Expertise when creating Modern UIs
KDAB assists you in the creation of user-friendly interfaces designed specifically for industrial process control, manufacturing, and fabrication.
Our specialties encompass the custom design and development of HMIs, enabling product accessibility from embedded systems, remote desktops, and mobile devices on the move.
Legacy software is a growing but often ignored problem across all industries. KDAB helps you elevate your aging code base to meet the dynamic needs of the future.
Whether you want to migrate from an old to a modern GUI toolkit, update to a more recent version, or modernize your code base, you can rely on over 25 years of modernization experience.
KDAB offers a wide range of services to address your software needs including consulting, development, workshops and training tailored to your requirements.
Our expertise spans cross-platform desktop, embedded and 3D application development, using the proven technologies for the job.
When working with KDAB, the first-ever Qt consultancy, you benefit from a deep understanding of Qt internals, that allows us to provide effective solutions, irrespective of the depth or scale of your Qt project.
Qt Services include developing applications, building runtimes, mixing native and web technologies, solving performance issues, and porting problems.
KDAB helps create commercial, scientific or industrial desktop applications from scratch, or update its code or framework to benefit from modern features.
Discover clean, efficient solutions that precisely meet your requirements.
Boost your team's programming skills with in-depth, constantly updated, hands-on training courses delivered by active software engineers who love to teach and share their knowledge.
Our courses cover Modern C++, Qt/QML, Rust, 3D programming, Debugging, Profiling and more.
The collective expertise of KDAB's engineering team is at your disposal to help you choose the software stack for your project or master domain-specific challenges.
Our particular focus is on software technologies you use for cross-platform applications or for embedded devices.
Since 1999, KDAB has been the largest independent Qt consultancy worldwide and today is a Qt Platinum partner. Our experts can help you with any aspect of software development with Qt and QML.
KDAB specializes in Modern C++ development, with a focus on desktop applications, GUI, embedded software, and operating systems.
Our experts are industry-recognized contributors and trainers, leveraging C++'s power and relevance across these domains to deliver high-quality software solutions.
KDAB can guide you incorporating Rust into your project, from as overlapping element to your existing C++ codebase to a complete replacement of your legacy code.
Unique Expertise for Desktop and Embedded Platforms
Whether you are using Linux, Windows, MacOS, Android, iOS or real-time OS, KDAB helps you create performance optimized applications on your preferred platform.
If you are planning to create projects with Slint, a lightweight alternative to standard GUI frameworks especially on low-end hardware, you can rely on the expertise of KDAB being one of the earliest adopters and official service partner of Slint.
KDAB has deep expertise in embedded systems, which coupled with Flutter proficiency, allows us to provide comprehensive support throughout the software development lifecycle.
Our engineers are constantly contributing to the Flutter ecosystem, for example by developing flutter-pi, one of the most used embedders.
KDAB invests significant time in exploring new software technologies to maintain its position as software authority. Benefit from this research and incorporate it eventually into your own project.
Start here to browse infos on the KDAB website(s) and take advantage of useful developer resources like blogs, publications and videos about Qt, C++, Rust, 3D technologies like OpenGL and Vulkan, the KDAB developer tools and more.
The KDAB Youtube channel has become a go-to source for developers looking for high-quality tutorial and information material around software development with Qt/QML, C++, Rust and other technologies.
Click to navigate the all KDAB videos directly on this website.
In over 25 years KDAB has served hundreds of customers from various industries, many of them having become long-term customers who value our unique expertise and dedication.
Learn more about KDAB as a company, understand why we are considered a trusted partner by many and explore project examples in which we have proven to be the right supplier.
The KDAB Group is a globally recognized provider for software consulting, development and training, specializing in embedded devices and complex cross-platform desktop applications.
Read more about the history, the values, the team and the founder of the company.
When working with KDAB you can expect quality software and the desired business outcomes thanks to decades of experience gathered in hundreds of projects of different sizes in various industries.
Have a look at selected examples where KDAB has helped customers to succeed with their projects.
KDAB is committed to developing high-quality and high-performance software, and helping other developers deliver to the same high standards.
We create software with pride to improve your engineering and your business, making your products more resilient and maintainable with better performance.
KDAB has been the first certified Qt consulting and software development company in the world, and continues to deliver quality processes that meet or exceed the highest expectations.
In KDAB we value practical software development experience and skills higher than academic degrees. We strive to ensure equal treatment of all our employees regardless of age, ethnicity, gender, sexual orientation, nationality.
Interested? Read more about working at KDAB and how to apply for a job in software engineering or business administration.
Today's blog post is about a small utility class in Qt with a... questionable name: QPointer. If you're new to Qt, maybe don't check out QPointer's documentation just yet, and try to guess what the class does based on its name alone.
I've seen countless users being very confused by it. Some end up using it extensively, thinking that it's the Qt way to store pointers, or a better kind of pointer, or maybe yet another Not Invented Here Qt class solving a non-problem, or something along those lines.
So what is QPointer?
QPointer is a weak pointer for QObjects. What's a weak pointer, you ask? A weak pointer is a smart pointer that does not participate in the ownership of a given object. Destroying the weak pointer has no effect whatsoever on the pointed-to object. Instead, a weak pointer acts as an observer, and is able to tell us whether the object has been already destroyed (by its owner(s)) or not.
QWidget *w =newQWidget(parent);// create a new object; `parent` owns itQPointer<QWidget> ptr = obj;// create a weak pointer, watching over *wQ_ASSERT(ptr);// ptr is valid, *w still exist destroyWidget();// destroy *w somehowQ_ASSERT(!ptr);// ptr is automatically reset,// to signal that *w is gone
In the snippet above it doesn't matter how exactly we destroy our object (an explicit delete, or through the parent object, etc.).
The interesting part is the last line: ptr knows that the object is destroyed, and automatically resets itself to a null pointer. Compare this with a "raw" C++ pointer, which does not get automatically reset, and would dangle instead.
Therefore, if we compose this a little bit further:
classMyClass{ QPointer<SomeObject> m_resource;// pointer to some resource we don't ownvoiddoSomething(){if(m_resource)// check that the resource is still alive; m_resource->use();// if so, use it}};
This is pretty interesting, because our code now is much safer (and simpler), compared to using raw pointers, or connecting to the QObject::destroyed() signal or some other mechanism.
Here's a very fancy scenario:
classMyObject:publicQObject{ Q_OBJECT
signals:voidaSignal(int value);public:voiddoSomething(){int value =calculateValue(); QPointer<MyObject>guard(this); emit aSignal(value);if(!guard)return;// do some other things}};
Here we're guarding against the fact then, when we emit a signal, slots connected to the signal may end up destroying the sender object. This usually doesn't have the form of delete sender, but it's more indirect. For instance, the sender may be a button, connected to a slot that re-arranges the UI of your application, and while doing so, it may end up destroying the button itself.
While deleting a sender object is supported by the signal/slot mechanism, it's important to realize that once all the slots connected to a signal have been called, the execution will continue in the code that emitted the signal. In there, the sender object (i.e. *this) is now destroyed. In the above snippet the guard lets the execution stop right after we return from the signal emission, in case we detect that *this has indeed been destroyed.
This pattern is used all over the place in widgets code (a place where the chances of deleting a sender are pretty high).
Please note: I'm not saying that you should protect all your signal emissions like the above. Deleting a sender object directly (via operator delete) is, generally speaking, a poor idea; one should use deleteLater() instead. Ideally here I'd like some debug mechanism from Qt telling us that we are indeed deleting an object in the middle of a signal emission, but I fear that the signal-to-noise ratio is going to be pretty close to 0.
QPointer is a weak pointer, std::weak_ptr is a weak pointer, are they different?
The principle behind QPointer and std::weak_ptr (or Qt's reimplementation, QWeakPointer) is pretty much the same: both are smart pointers classes pointing to object that are not owned through that smart pointer. There's however some important differences.
1. QPointer only works with QObject subclasses; std::weak_ptr works with any type.
This isn't an "arbitrary" limitation put in place by QPointer; it has strictly to do with how these weak pointer classes detect that the resource they're observing has been destroyed.
std::weak_ptr achieves this because it observes the control block that another smart pointer class set up for it: std::shared_ptr. That's right, std::weak_ptr and std::shared_ptr go hand-in-hand; you must manage a given resource with std::shared_ptr in order to use std::weak_ptr with it. This is because std::weak_ptr observes the strong counter in the control block in order to know if the resource is still alive. This is a (very simplified!) example of how std::shared_ptr and std::weak_ptr work together:
On the other hand, a QObject observed by QPointer doesn't have to be managed in any specific way. It can be owned using a raw pointer, or by an owning smart pointer class, or through QObject's parent/child mechanism, or it can be a data member of another class... It doesn't matter: QPointer simply doesn't impose a particular owning strategy.
So how does QPointer know when the object it points to has been destroyed? QPointer needs some help from that object. Specifically, that object is going to set up a control block so that QPointer can then use it. This is what happens inside QObject guts (see the sharedRefcount member of QObjectPrivate and its usages).
And this is why QPointer requires the pointed-to type to be a QObject (subclass): it needs some special logic that only QObject implements.
By the way, if you're curious: the mechanism used behind the scenes by QObject and QPointer is actually exactly the very same one that in Qt is used by QSharedPointer and QWeakPointer: a control block with two counters, the strong counter and a weak counter. The strong counter signals whether the QObject has already been destroyed (it's not really used as a "counter" in this scenario; it's actually set to -1, and reset to 0 when the object is destroyed); the weak counter counts how many QPointer objects are tracking a given QObject. Here's how it looks like:
Again, this is a simplification. I'm deliberately omitting some details such as the fact that the control block also stores the deleter, a pointer back to the object, and especially whether the weak counter only tracks weak pointers or the sum of strong pointers and weak pointers.
From this point of view, QPointer acts as an intrusive pointer, expecting the pointed-to object to obey a certain protocol. This is vaguely similar to the (in)famous std::enable_shared_from_this class template, that allows one to create shared pointers (and weak pointers, as of C++17) out of an arbitrary object, because the object itself keeps a pointer to the control block used to manage it. (It does so by inheriting from std::enable_shared_from_this). However, std::enable_shared_from_this on an object which is not already managed by a shared pointer will not magically start the refcounting process, while instead QPointer does so.
And while at it, here's another little nugget: the fact that this specific implementation was used by QPointer is also why QWeakPointer supported direct construction from QObjects back in Qt 5, even if they were not managed by a QSharedPointer. This has made a lot of people very angry and been widely regarded as a bad move.
2. QPointer doesn't use a lock()ing protocol
If you have a weak pointer, how do you use it? The whole purpose of such a smart pointer class is to let you test if the pointed-to object is still alive, and only if it is, use it.
Therefore, one can try a strategy like this one:
WeakPointer<Foo> weakPtr;// declared somewhere// Here's how one would use it:if(weakPtr)// is the object still alive? weakPtr->doSomething();// use it!
This specific snippet looks OK, but actually it doesn't even compile with std::weak_ptr. The reason is that code written like this could exhibit a TOCTOU bug: even if the check passes, by the time we try to use the object, the object could've been destroyed.
How in the world could the object disappear between the if and the usage? But because of multiple threads, of course! std::shared_ptr and std::weak_ptr's reference counting mechanism is thread safe. (The reference counting is; the objects themselves are merely re-entrant.) So while you execute the above snippet in thread 1, thread 2 could be destroying the last shared pointer owning the object, therefore destroying the object. If thread 2 happens to do this right between the check of the weak pointer by thread 1 and its subsequent access, your program is in trouble.
This is why, when dealing with std::weak_ptr, we ask "is the object still alive?"; but we word the question slightly differently. We ask "can I become a co-owner of the object, if it's still alive?"
Becoming a co-owner means getting a std::share_ptr pointing to the object; therefore we are going to call a function that will return one. We somehow ask to "upgrade" our status: from mere observer (std::weak_ptr) to co-owner (std::shared_ptr). The returned std::shared_ptr object will be loaded in case the object is still alive, or empty in case the object has already been destroyed. Now, for a number of reasons, this "upgrade request" has a very weird name: it's called std::weak_ptr::lock() (docs). In my humble opinion, this just gets C++ newcomers very confused, as they immediately think about mutex locking or some other multithreading primitives that have no role in what's happening here.
Now, being a co-owner is a pretty good thing for us, because it means that we can safely check if the object is still alive (by checking the returned shared pointer). If the object is alive, we can safely access it: no other threads can now lose the last owning pointer to our object and destroy it under our nose. There's always at least one owner: yourself, through the std::shared_ptr you've just obtained. Hence, the code above has to spelled like this when using std::weak_ptr:
std::weak_ptr<Foo> weakPtr;// declared somewhere// Test and use:std::shared_ptr<Foo> sharedPtr = weakPtr.lock();if(sharedPtr)// sharedPtr, not weakPtr! sharedPtr->doSomething();// object is alive, use it
What about QPointer? Well, QPointer lets you get away with it:
QPointer<MyQObject> ptr;if(ptr)// is the object still alive? ptr->doSomething();// use it!
Doesn't this code suffer from the problem that weak_ptr works so hard to prevent? Well yes, it does. However, in practice it does not constitute a problem, because we are never supposed to touch QObjects from arbitrary threads -- and this includes deleting them.
If we stick to a single-thread scenario, the code above works just fine. This is why I keep repeating that, although QObject is technically speaking reentrant, it's better to treat it as thread-unsafe: only use a QObject from one thread (the thread the object lives into, or has affinity with).
Here's the full details in case you want to know more:
To watch this video on our website please or view it directly on YouTube
Conclusions
That's it for today's blog. I hope I've explained what QPointer does, and when to use it.
There's only one thing missing, which is the title of the blog post: why is QPointer a pretty bad name?
In my opinion, it should have been called for what it is: a weak pointer for QObject subclasses. So, how about QObjectWeakPointer? It's not that Qt strives for very short names anyhow (hello, QXmlStreamNotationDeclaration); giving it a more descriptive name would remove confusion and actually ease discoverability.
Thank you for reading, and I'll see you next time.
About KDAB
Trusted software excellence across embedded and desktop platforms
The KDAB Group is a globally recognized provider for software consulting, development and training, specializing in embedded devices and complex cross-platform desktop applications. In addition to being leading experts in Qt, C++ and 3D technologies for over two decades, KDAB provides deep expertise across the stack, including Linux, Rust and modern UI frameworks. With 100+ employees from 20 countries and offices in Sweden, Germany, USA, France and UK, we serve clients around the world.
Senior Software Engineer at KDAB. Giuseppe is a long-time contributor to Qt, having used Qt and C++ since 2000, and is an Approver in the Qt Project. His contributions in Qt range from containers and regular expressions to GUI, Widgets, and OpenGL. A free software passionate and UNIX specialist, before joining KDAB, he organized conferences on opensource around Italy. He holds a BSc in Computer Science.
Our hands-on Modern C++ training courses are designed to quickly familiarize newcomers with the language. They also update professional C++ developers on the latest changes in the language and standard library introduced in recent C++ editions.