Automatic deletion of class member variables in QT
-
Hi All
I have classclass myShortCut class myShortCut: QShortCut { myShortCut(QWidget* parent = 0 ) ; ~myShortCut() { qDebug() << "\n I am in Destruct or of myShortcut" ; } private: int *i; }; // constructor of myShortCut myShortCut::myShortCut(QWidget* parent):QShortcut(QKeySequence(Qt::CTRL + Qt::Key_R),parent) { i = new int; *i = 1; qDebug() << " In constructor of myShortCut"; } // class myView class myView : public QTextEdit { Q_OBJECT public: myView(QWidget* parent); ~myView(); myShortcut* shortCut }; myView ::myView () { shortCut = new QShortCut(this) } myView ::~myView () { }
When I close the gui the Even if I do not delete the shortCut member variable in destruct or of myView , the destructor of myShorcut is called
Also I tried to put a delete shortCut in destructor of myView
myView ::~myView () { delete shortCut }
then also he destructor of myShorcut is called
Can someone comment of how automatic deletion class variables works in QT when the gui is close
[Fixed code formatting. ~kshegunov]
-
@Qt-Enthusiast said:
Can someone comment of how automatic deletion class variables works in QT when the gui is close
This has no relation to the GUI.
QObject
instances will delete their children in the destructor ensuring that child objects are not left dangling in memory (i.e not leaking memory). By giving a parent to aQObject
subclass (QShortcut
here):shortCut = new QShortcut(this)
you're also adding the newly created object as a child to
this
(being of typemyView
in this case). Ultimately when the destructors are called the shortcut will be deleted. -
Two more questions
-
What if I have following code.. Will shortCut variable will be deleted automatically
myView ::myView () {
shortCut = new QShortCut
} -
Also What if shortCut is a local variable instead of class variable then ?
-
Could you point me the documentation when such concept is mentioned , regarding Q_Object automatically deletes its children
-
-
What if I have following code.. Will shortCut variable will be deleted automatically
No, because there's no parent specified, so the
QObject
will not be owned by anotherQObject
, thus no one will be bound to deleting it automatically.Also What if shortCut is a local variable instead of class variable then ?
As any C++ stack allocated local variable, going out of scope (unwinding the stack) will free the memory after running the corresponding destructors. As for heap allocations - it's up to the programmer to manage the heap, so no automatic deletion shall be happening when a local pointer goes out of scope.
Could you point me the documentation when such concept is mentioned , regarding Q_Object automatically deletes its children