What are the main differences between the use of QObject memory management and smart pointers? When is it better to use this or that mechanism?
As you probably know, at destruction QObject will destroy all their children, this is what we call "QObject memory management". Children are typically added to a QObject *parent from their constructor with new QObject(parent);.
Smart pointers on the other hand, is more a category than a specific type, including shared pointers, auto pointers, etc. which have an implementation in both the STL and Qt in C++ (only to name those two).
So even though they are not directly comparable, I would sum it that way:
You don't need/want to store the pointer
MyObject *object = new MyObject(this);
object->setSomething();
// And you don't ever need to access it later
Your object only tied to its parent lifespan. In that case, you won't need to create an additional smart pointer over it, and you will be able to store it as a simple QObject*
You need the QObject hierarchy and/or find features, which let you do stuff like below. See QObject documentation for more details.
// Get children
auto childrenList = this->children();
// Find a specific child
MyObject* child = this->findChild<MyObject*>("specific name");
If you fall in one of these cases and your object is shared, you might want to use QObjectPointer type too, which will be automatically reset whenever the pointed QObject is destroyed.
QObject based type, of courseQScopedPointer or std::unique_ptr. QObject parenting would be most likely overkill here, and dangerous.QSharedPointer or std::shared_pointer/std::weak_ptr. Again, QObject parenting could delete your QObject at any time, which is not what you want when using shared pointers.Then it is up to you, they serve different purposes.
QObject parenting: simple, and will nicely integrate with Qt code. Careful as the call stack will be a little less clear to understand if you are debugging though.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With