Qt objects which are allocated with new
are pretty much handled for you. Things will get cleaned up at some point (almost always when the parent gets destructed) because Qt objects have a nice parent child relationship.
So my question is this: given that some widgets exist for the life of the application, is it considered good/beneficial to limit the scope of some child widgets? It seems to me that if I don't the application may not release these objects until the ap开发者_如何转开发plication exits. For example:
MyMainWindow::contextMenu(...) {
QMenu *menu = new QMenu(this);
// ...
menu->exec();
}
vs:
MyMainWindow::contextMenu(...) {
QMenu *menu = new QMenu(this);
// ...
menu->exec();
delete menu;
}
vs:
MyMainWindow::contextMenu(...) {
QScopedPointer<QMenu> menu(new QMenu(this));
// ...
menu->exec();
}
I like the last one the best, i know that that menu object will be cleaned up immediately, without adding any lines of code to worry about. But, in the first one, it should be cleaned up eventually. Am I wasting my effort trying to manage the lifetime of these Qt widgets? Should I just leave it up to Qt entirely?
In your first example, menu will be deleted when this (i.e. the MyMainWindow object) is... which is probably not what you want, since that means that if contextMenu() is called more than once, multiple unseen old QMenu objects will build up in memory, and might eventually use up a lot of RAM if the user never closes/deletes the MyMainWindow for a long time.
Your second and third examples are both fine. The third is probably slightly better, since it avoids any possibility of a bug ever being introduced where the delete doesn't get called.
I try to clean up all the objects if their scope is significantly different than the parent object. I like either your second or third options, and would like to propose a fourth:
MyMainWindow::showMyDialog() {
QDialog *d = new MyDialog(); // Oftentimes parents don't make sense for dialogs
d->setAttribute( Qt::WA_DeleteOnClose );
// ... presumably connect signals/slots here
d->show();
} // d isn't deleted yet, but will be once the dialog is accepted or rejected
// (and all corresponding signals are emitted).
精彩评论