开发者

Why does wxWidgets not leak Frames?

开发者 https://www.devze.com 2023-03-11 05:58 出处:网络
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:

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.


Cleanup is discussed here: http://docs.wxwidgets.org/2.9.2/overview_windowdeletion.html


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消