PDA

View Full Version : QT memory managment



MarcoG3
22nd November 2012, 23:04
Consider the following snippet code:


1: QPushButton *p_Button = new QPushButton(this);
2: QPushButton myButton(this);

Line 1: this is referred to QWidget, so p_Button is child of QWidget in my example: when QWidget dies (goes out the scope??) his destructor deletes p_Button from the heap and calls the destructor of p_Button.

Line 2: Same as Line 1, but does the destructor of QWidget delete myButton since its child is also myButton?

Please correct me if I stated something wrong and reply to my questions.

ChrisW67
22nd November 2012, 23:24
In line with standard C++ rules myButton is deleted when it goes out of scope. MyButton ceases to exist and is destroyed before its parent can be destroyed; this will remove it from the child list of its Qt parent. When the parent is finally destroyed MyWidget no longer exists as a child to delete.

MarcoG3
22nd November 2012, 23:36
Could I delete p_Button manually before QWidget delete it? I'd probably need to delete it when I won't need it anymore and to not cause memory leaks?

ChrisW67
23rd November 2012, 04:29
Yes... and you can try this for yourself with a short program. Each QObject emits the QObject::destroyed() signal as it is destroyed, and the QObject parent (if there is one) uses this to remove the disappearing QObject from its list of children.



#include <QtCore>
#include <QDebug>

class Object: public QObject {
Q_OBJECT
public:
Object(const QString &s, QObject *p = 0): QObject(p) {
qDebug() << "Creating object" << s << "parent" << p;
setObjectName(s);
}
~Object() {
qDebug() << "Destroying" << objectName() << "with children" << children();
}
};

int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
Object parent("Parent");
Object o1("Stack child", &parent);
Object *h1 = new Object("Heap Child 1", &parent);
Object *h2 = new Object("Heap Child 2", &parent);
delete h1;
qDebug() << "Bye!";
return 0;
}
#include "main.moc"