Nominate our 2022 Qt Champions!

[SOLVED] Understanding memory management in some Qt classes

  • Hi,

    The way I understand the documentation about memory management is that you can either use a QPointer or use the parent/keyword "this" when creating an object that inherits QObject. Well up until now I have been trying to use the last method I described which is basically adding the "this" keyword as the parent every time I create an object in the heap with the keyword new().

    I just noticed that QStandardItem does not have a parameter to indicate what the parent is and this got me wondering if the following code would be considered a dangling pointer or memory leak.

    @QStandardItem *someVar = new QStandardItem(someString);@

    What would be the right way to prevent a memory leak when using QStandardItem? Should I delete it in the deconstructor?
    delete ui;
    delete someVar;// deleting it here
    } @

    Sorry if my poor understanding about memory management doesn't even make sense but I'm just starting to put more attention about memory management.

    Thanks a lot.

  • There are many ways to manage memory:

    • Don't use new unless you have to.
    • Smart pointers
    • Setting the parent if it inherits QObject
    • Manually delete (not recommended because error-prone, etc...)

    In the specific case of QStandardItem, I assume you will place it in QStandardModel, in which case the QStandardModel will delete that pointer for you.

    Best to pick up a general book about C++ if you're new to this though.

  • When you add an item (QStandardItem) to a model (QStandardItemModel) the model takes the ownership of the items and similarly when you add your model to an ItemView the ItemView takes the ownership of the model, So when you delete the ItemView then its automatically deletes its child objects.

    Similarly if you initialize an ItemView with this as parameter the deletion will be automatically handled by the parent class.

  • Make a lot of sense, thanks a lot.

  • By the way QPointer does not delete the data. So if you are using QPointer, you are still leaking memory.

  • Thank you for the clarification.

    Any recomendation on a book or tutorial on general memory management in c++?


  • Yeeah, it looks like a good resource. Thanks a lot.

Log in to reply