2011-11-15 38 views
0

此代碼工作正常:wxWidgets的是OnInit

#include <wx/wx.h> 

class MyApp : public wxApp 
{ 
    virtual bool OnInit(); 
}; 

IMPLEMENT_APP(MyApp) 

bool MyApp::OnInit() 
{ 
    wxFrame *frame = new wxFrame(NULL, -1, _("Hello World"), wxPoint(50, 50), 
            wxSize(450, 350));  
    frame->Show(true); 
    return true; 
} 

但這並不:

#include <wx/wx.h> 

class MyApp : public wxApp 
{ 
    virtual bool OnInit(); 
}; 

IMPLEMENT_APP(MyApp) 

bool MyApp::OnInit() 
{ 
    wxFrame frame(NULL, -1, _("Hello World"), wxPoint(50, 50), 
            wxSize(450, 350));  
    frame.Show(true); 
    return true; 
} 

它不給任何編譯/鏈接/執行錯誤,就是不現身窗口。爲什麼這個?

回答

1

Show函數立即返回,因此wxFrame對象立即被銷燬(因爲它是在堆棧上創建的) - >所以沒有什麼可顯示的。

如果使用new創建框架,則在退出該功能後該對象不會被銷燬。

0

你不應該在堆棧上創建wxWindow類(wxFrame,panel等),你應該只在堆上創建它。這在wikidocs中有詳細解釋。

INS's answer也是正確的,但創建wx應用程序的唯一方法是不通過內存泄漏。程序執行完成後,wxWidgets自動刪除它的wxWindow類。所以這就是爲什麼我們不刪除類(也不是你使用的wxApp)。對於其他對象,可以使用wxApp :: OnExit()函數手動刪除堆中的任何其他數據。

#include <wx/wx.h> 

class MyApp : public wxApp 
{ 
public: 
    virtual bool OnInit(); 
    virtual int OnExit(); 

private: 
    wxFrame *m_frame; 
    int *m_foo; 
}; 

IMPLEMENT_APP(MyApp) 

bool MyApp::OnInit() 
{ 
    m_frame = new wxFrame(nullptr, -1, wxT("No leaks"), wxPoint(-1, -1), 
          wxSize(300, 200)); 
    m_frame->Show(true); 
    m_foo = new int(2); 

    return true; 
} 

int MyApp::OnExit(){ 
    // Any custom deletion here 
    // DON'T call delete m_frame or m_frame->Destroy() m_frame here 
    // As it is null at this point. 
    delete m_foo; 
    return 0; 
}