2008年11月22日星期六

Construction/Destruction Order of QObjects


int main()
{
     QPushButton quit("Quit");
     QWidget window;
     quit.setParent(&window);
     ...
 }

In this case, the order of destruction causes a problem. The parent's destructor is called first because it was created last. It then calls the destructor of its child, quit, which is incorrect because quit is a local variable. When quit subsequently goes out of scope, its destructor is called again, this time correctly, but the damage has already been done.

Remember: When the destructor of the child(quit) is called first, it removes itself from its parent(window), before the destructor of parent is called. Anyway the child will not be called twice. You MUST "delete" the object manually which is created with "New" and don't have a parent!

没有评论: