Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QObject memory management and smart pointers [closed]

Tags:

c++

qt

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?

like image 906
Denis Scherbakov Avatar asked Mar 15 '26 15:03

Denis Scherbakov


1 Answers

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:

Use QObject memory management when ...

  1. Your object is a QWidget, of course, or GUI related
  2. 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
    
  3. 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*

  4. 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.

Use smart pointers when ...

  1. Your object is not a QObject based type, of course
  2. Your object is local (deleted at the end of the scope), in which case you need a QScopedPointer or std::unique_ptr. QObject parenting would be most likely overkill here, and dangerous.
  3. Your object is shared, and thus requires a 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.

None of the above?

Then it is up to you, they serve different purposes.

  • In Qt GUI related code, I tend to prefer 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.
  • Outside of the UI, or to interface with non-UI related code, I prefer pure C++: The less external dependencies, the better!
like image 98
Adrien Leravat Avatar answered Mar 18 '26 04:03

Adrien Leravat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!