今天用Fox Toolkit编写了一个小Demo程序,但在程序运行结束时,总会出现内存出错的提示。其部分代码如下:
TestWindow::TestWindow(FXApp* a):FXMainWindow(a,"Test Window",NULL,NULL,DECOR_ALL,0,0,800,600)
{
// Menu bar
menubar=new FXMenuBar(this,LAYOUT_SIDE_TOP|LAYOUT_FILL_X);
// File menu
filemenu=new FXMenuPane(this);
new FXMenuCommand(filemenu,"Quit/tCtl-Q",NULL,getApp(),FXApp::ID_QUIT);
new FXMenuTitle(menubar,"&File",NULL,filemenu);
// Status bar
status=new FXStatusBar(this,LAYOUT_SIDE_BOTTOM|LAYOUT_FILL_X|STATUSBAR_WITH_DRAGCORNER);
// Main window
contents=new FXVerticalFrame(
this,
LAYOUT_SIDE_TOP|FRAME_NONE|LAYOUT_FILL_X|LAYOUT_FILL_Y);
leftFrame=new FXVerticalFrame(
contents,
FRAME_SUNKEN|LAYOUT_FILL_X|LAYOUT_FILL_Y|LAYOUT_TOP|LAYOUT_LEFT,
0,0,0,0,10,10,10,10);
.......
}
TestWindow::~TestWindow(){
delete filemenu;
delete menubar;
delete contents; /*注意这里的顺序是错误的*/
delete leftFrame;
}
之所以出现内存出错,是因为TestWindow类的析构函数中各组件的释放顺序。上述代码中,leftFrame是依据contents建立的,即leftFrame是在contents容器中。因此,当delete contents后,再delete leftFrame就会因为找不到contents而出现内存出错的提示,delete不成功。
了解了原因之后,只需将这里的delete顺序更改一下即可,先delete leftFrame再delete contents。如果contents容器中同样存在其他组件,则必须先将这些组件delete完后,才可delete contents。其他容器的释放顺序也需按照这一规则。