Delete is not required after new in Qt. qtdelete

Source: Internet
Author: User

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 ;}




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.