Bob
Bob

Reputation: 1

wxWidgets OnInit

This code works fine:

#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;
}

But this doesn't:

#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;
}

It doesn't give any compilation/link/execution error, just don't show up the window. Why this?

Upvotes: 0

Views: 1586

Answers (2)

JohnJohn
JohnJohn

Reputation: 343

You're not supposed to create wxWindow classes (wxFrame, panel etc.) on stack, you should only create it on heap. It is explained in detail in thewiki and in the docs.

INS's answer is also correct, but the only way to create a wx application is NOT through a memory leak. wxWidgets deletes it's wxWindow classes automatically after the program has finished executing. So that's why we're not deleting the class (nor the wxApp you're using). For the rest of the objects you can use the wxApp::OnExit() function for manually deletion of any other data on heap.

#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;
}

Upvotes: 1

INS
INS

Reputation: 10820

The Show function returns immediately so the wxFrame object is destroyed right away (as it is created on stack) -> so there is nothing to display.

If you create the frame using new the object is not destroyed after exiting the function.

Upvotes: 1

Related Questions