[SOLVED] Understanding memory management in some Qt classes
-
wrote on 10 Oct 2013, 02:02 last edited by
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?
@MainWindow::~MainWindow()
{
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.
-
wrote on 10 Oct 2013, 05:44 last edited by
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.
-
wrote on 10 Oct 2013, 05:51 last edited by
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.
-
wrote on 10 Oct 2013, 09:40 last edited by
Make a lot of sense, thanks a lot.
-
wrote on 10 Oct 2013, 11:00 last edited by
By the way QPointer does not delete the data. So if you are using QPointer, you are still leaking memory.
-
wrote on 11 Oct 2013, 01:34 last edited by
Thank you for the clarification.
Any recomendation on a book or tutorial on general memory management in c++?
Thanks
-
wrote on 11 Oct 2013, 04:16 last edited by
I would start here
http://www.parashift.com/c++-faq/dtors.html
http://www.parashift.com/c++-faq/freestore-mgmt.htmland google for RAII.
-
wrote on 11 Oct 2013, 10:48 last edited by
Yeeah, it looks like a good resource. Thanks a lot.
1/8