下面的代码运行良好:
#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;
}它不会给出任何编译/链接/执行错误,只是不会显示窗口。为什么是这个?
发布于 2011-11-25 20:48:51
Show函数会立即返回,因此wxFrame对象会立即销毁(因为它是在堆栈上创建的) ->,所以不会显示任何内容。
如果使用new创建帧,则对象在退出函数后不会被销毁。
发布于 2017-08-23 10:22:17
您不应该创建wxWindow类(wxFrame、panel等)。在堆栈上,你应该只在堆上创建它。在wiki和docs中有详细的解释。
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;
}https://stackoverflow.com/questions/8137371
复制相似问题