Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ QT Memory Allocation [duplicate]

Tags:

c++

qt

Possible Duplicate:
Memory management in Qt?

I have been learning Qt and there was a discussion if the pointers to Q objects such as QLabel should be deleted. Does Qt have automatic memory management for pointers to Qt objects or must they be deleted manually?

ex)

#include <QApplication>
#include <QLabel>

int main(int argc, char *argv[])
{

 QApplication app(argc, argv);

 QLabel *label = new QLabel("Im Tough.");

 label->show();

 int result = app.exec();

 //would this be necessary or would QT handle this automatically?
 delete label;

 return result;
}
like image 356
lambda Avatar asked Jan 09 '13 05:01

lambda


2 Answers

If the object has a parent, you don't need to release it - it will be done automatically by the QT memory management system.

In your specific example, you do need to delete your object, since it has no parent. Even if you do not do it, it will be done by your OS when app.exec(); returns.


From the documentation about the qt's object trees :

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.

like image 54
BЈовић Avatar answered Oct 18 '22 00:10

BЈовић


If QLabel has parent it will be deleted on its parent deleting, otherwise you should do it on your own. More: http://doc.qt.digia.com/qt/objecttrees.html

like image 30
Arsenii Fomin Avatar answered Oct 18 '22 00:10

Arsenii Fomin