Delete is not required after new in Qt. qtdelete
Delete is not required after new in Qt. The parent-child object mechanism of QT is implemented in QWidget and QOject. When we create an object using the parent object, the parent object will add this object to its own sub-Object List. When this parent object is deleted, it will traverse its sub-object class table and delete each sub-object. Then, the sub-objects themselves will delete their own sub-objects, in this way, the call is recursive until all objects are deleted.
This parent-child object mechanism will greatly simplify our memory management and reduce the risk of Memory leakage. We need to explicitly DELETE objects (that is, objects deleted using delete) that are created using NEW and have no parent object (DELETE is required only for new objects, objects obtained through member functions are not explicitly described. Do not delete objects randomly .). If we delete an object before deleting its parent object, QT will automatically remove it from its parent object sub-Object List.
An example is as follows:
# Include "mainwindow. h" # include
# Include
# Include
Int main (int argc, char * argv []) {QApplication a (argc, argv); MainWindow w; QLabel * label = new QLabel ("hello", & w ); // delete is not required after new is used here, because the label's parent class is w, while w is created in the stack and will be automatically released when the program is closed, therefore, the sub-class memory of w is also released. QLabel * label1 = new QLabel ("world"); // delete label1 is required. Otherwise, memory leakage occurs because the label does not have a parent class, therefore, no memory w is released for the label. show (); a.exe c (); delete label1; label1 = NULL; return 0 ;}