10
votes

I'm trying to learn wxWidgets, but I'm stuck on a point which I can't find an explanation for anywhere in the documentation. I am trying to understand this minimal wxWidgets program:

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

Specifically, why is it that frame does not leak? When does it get released and whose responsibility is is? In a normal program a pointer that does not get passed to anything and that goes out of scope without being deleted is almost certainly a leak, but apparently this is not so in wxWidgets.

3
It might register itself with the framework, to be deleted when the window is closed. - Bo Persson
@Xeo This code comes directly from the example code in the documentation (cut down for emphasis). I can't find any example code in which the frame is deleted so I am assuming that it does get deleted somehow. At the same time I can't find anything in the documentation that specifically says that the Frame will be deleted, so I'm hoping someone on SO has the full story. - Mankarse
Augh- I found the full answer here. - Mankarse

3 Answers

3
votes

See the note in the Hello World example on the wxWidgets wiki:

http://wiki.wxwidgets.org/Hello_World

"You could be wondering why the frame variable isn't deleted anywhere. By setting the frame as the top window of the application, the application will delete the frame for us (for a more in-depth explanation, see Avoiding Memory Leaks)."

However, the code you posted doesn't call SetTopWindow() the way the code from the wiki does. So I imagine it would leak.

-1
votes

A memory leak occurs when a program keeps on allocating memory and never releasing it. Eventually such a program will run out of new memory to allocate and stop.

MyApp::OnInit() is called once at program start up. The memory for frame is allocated once and kept allocated until the program ends, which is exactly what you need to happen. There is no memory leak because the new wxFrame in OnInit() is called just once.

It may well be that wxWidgets registers the wxFrame pointer and looks after tidying it up if the program shuts down gracefully. That would be nice, but makes no practical difference.