简体   繁体   中英

Which memory management method should we use in Qt?

I'm quite new to programming as I'm still learning how to code efficiently so my question may seem a little bit strange.

As I'm learning how to code with Qt, I know that Qt has a memory management method that the parent deletes all its children when it itself was deleted, and then there's QSharedPointer and so many other smart pointer thing (or you may mention boost::shared_ptr ).

I understand how exactly both methods work but my question is that when it comes to the design of the whole system structure in Qt, should i make most of my class a subclass of QObject and hand over the ownership to QT to do the memory management, or simply using boost::shared_ptr or QSharedPointer thing to avoid potential memory leaks ?

As there's a lot of problem to take into account if we adopt both techniques because it may cause double-delete problem.

So which technique has better performance or which is better in the design?

As you know, Qt has a model for which:

QObjects organize themselves in object trees. When you create a QObject with another object as parent, it's added to the parent's children() list, and is deleted when the parent is.

Moreover:

You can also delete child objects yourself, and they will remove themselves from their parents.

Because of that, as long as you use that model, you won't have problems of double frees.

That said, a common approach I've seen and used (but be aware that there was ever a reason to do that) is to create two layers, the former as a purely Qt-based one and the latter completely Qt-unaware. Of course, it requires a thin layer that translate pieces of information back and forth.
In such a model, it is reasonable to see both the approaches applied, never mixed and correctly working.

So, which is the best one? It depends on your target.

I've used a mixed approach in cases where the underlying layer was meant as a standalone codebase on top of which I was able to create an interface using my preferred library, but also I wanted to be free to switch to whatever library for the UI.
If this is not the case and your project is a purely Qt-based one, there is no reason not to base everything on the model on which Qt itself is based.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM