PDA

View Full Version : Dynamically allocated objects



DmitryNik
25th September 2011, 14:17
Hello!

May be it will be a stupid question, but I want to know it for sure.
Does the same principle work in QT as in C++: what was created dynamically, suppose to be deleted with a help of key-word "delete"?
For instance, I have the next line of code: QListView *_lv = new QListView; Will be deleted automatically _lv-variable or in the end I suppose delete it by myself?
And next example: I have my own class "myClass" which is derived from, let say, QGraphicsItem and the next line of code: myClass *_mc = new myClass();. The question is the same.

Thank you beforehand for answers.

Zlatomir
25th September 2011, 14:30
The answer is the same for both questions:

If you have only QListView *lv = new QListView; and lv doesn't get a parent (for example by adding it into a layout) you should call delete.

But if you have QListView *lv = new QListView(SomeWidgetPointer); then lv gets deleted when SomeWidgetPointer gets deleted - either by it's parent or by a delete call or gets out of scope (if the parent is allocated on stack)

So basically you need to make sure the QWidgets (and other QObject derived classes) get a parent and then you need to make sure you delete the top-most parent (or allocate it on stack - for example in main function)

//hope i was clear enough

DmitryNik
25th September 2011, 14:39
Thank you. Nice to know such things for preventing memory leaking.

ChrisW67
25th September 2011, 23:43
You are responsible for delete-ing anything you allocate in C++, Qt does not change that. If the thing you allocate is a QObject with a parent (or give it to something that sets the parent) then the QObject parent-child hierarchy looks after it for you. For other objects you allocate you can look at Qt's QScopedPointer and QSharedPointer, which are roughly similar to the std::auto_ptr and std::tr1::shared_ptr, to help with this task.

joseluis
26th September 2011, 12:20
When your object has a parent, if you do not delete it, it will be deleted by parent