简体   繁体   中英

Qt memory management

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.

Yes and yes. If a QObject is not created by new, it must be destroyed before its parent. Otherwise, the parent will delete the child and the program may crash.

Qt has some good documentation on object trees and ownership that explains this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM