Where to free dynamic allocated widgets, generated within signal handlers



I want to write an application which sometimes should create new top
level windows by user interaction. As this, the user e.g. press a button
and a new window should be opened. Later on, the user should be able to
close that new top level window.

Where I can safely "free" the resources of the window. Currently I
simply derive from a Gtk::Window and do the stuff, but I have no idea
where I can call free on the window pointer which was allocated with new
in the signal hanlder from the button.

Maybe there is a better way to create a new window without having that
problem?

See the following example code:



#include <iostream>
#include <string>
#include <gtkmm.h>


class ExampleWindow : public Gtk::Window
{
    protected:

        //Child widgets:
        Gtk::Box m_VBox;
        Gtk::Button m_button;
        std::string mytext;

    public:
        ExampleWindow(const std::string& text_):
            m_VBox{ Gtk::ORIENTATION_VERTICAL }
        ,m_button{ text_ }
        ,mytext{ text_ }
        {
            set_title("Example");
            set_border_width(10);
            set_default_size(400, 200);

            add(m_VBox);

            m_VBox.pack_start( m_button );

m_button.signal_clicked().connect(sigc::mem_fun(this,&ExampleWindow::on_clicked));

            show_all_children();
        }

        void on_clicked()
        {
            ExampleWindow* win2 = new ExampleWindow("Stand Alone Win");
            win2->show();   // How can I desruct this window, if a user
closes it?
        }


        virtual ~ExampleWindow()
        {
            // Not called for the stand alone win while closing it. How
to achieve that?
            std::cout << "Destructor called for " << mytext << std::endl;
        }

        bool on_delete_event( GdkEventAny* ) override
        {
            std::cout << "sighandler on_delete called"  << mytext <<
std::endl;
            //free(this); // results in segfault
            return false;
        }

};


int main(int argc, char *argv[])
{
    auto app = Gtk::Application::create(argc, argv, "some.base");

    ExampleWindow window{ "Press to create new win" };

    //Shows the window and returns when it is closed.
    return app->run(window);
}


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]