QT4 Memory Management
c++, memory-management, qt, qt4
Solution
If I create a QList and add objects to it, and then the QList goes out of scope, will it try to deallocate the child objects?
QList is just like std::list. It will destroy the contained objects when it is destroyed.
If a Qt4 routine returns a pointer to an object, am I then responsible for the de-allocation of that object?
Usually no, the docs should specify what happens. An exception are the take* functions (e.g: QTableWidget::takeItem).
If I create a subclass of a QWidget, and add it to a QWindow, how do I insure that when the QWindow is destroyed, that it takes my widget with it?
It depends on how you create the subclass object.
- You could add it as a member of the window widget (there is no QWindow, by the way) and it will be destroyed just like any member variable.
- You could allocate it with new and pass it the window as parent and it will be deleted thanks to the Qt object tree implementation (as cake mentioned)
- You could do the memory management yourself.
When a QWidget (or any QObject) is destroyed, it will remove itself from its parent's to-delete list so you can delete it yourself and not worry about double deletes.
Problem
I come from a fairly strong C background, and have a rather solid foundation in C++. More recently I've been working with C# and other higher level languages. A project I'm looking at working on could really benefit from using QT4, but I have some questions on memory management I can't seem to understand. I've read the QT4 documentation and it hasn't helped me much. So that is why I'm here. 1) Okay so to start with, I understand that the easiest way to use QT4 objects is to declare them locally: ``` void MyFunc() { QString foo; // do stuff to foo } ``` This is simple enough, I can take that object, and pass it around and know that when it goes out of scope it will be destroyed. But here's my question. 1)If I create a QList and add objects to it, and then the QList goes out of scope, will it try to deallocate the child objects? 2)If a QT4 routine returns a pointer to an object, am I then responsible for the de-allocation of that object? 3)If I create a subclass of a QWidget, and add it to a QWindow, how do I insure that when the QWindow is destroyed, that it takes my widget with it? Thanks for the help.