Search code examples
c++gtkgnomegladegtkmm

Memory management of GTK+ objects using Glade and gtkmm


I am using C++ to create a program using GTK+ and glade. I am concerned about the memory management of the objects that the glade creates. For example, I create a glade file consisting of a window, a button and two entry fields. Then in my C++ code I create an object from that file and get a pointer to that window. My question is, do I have to safely deallocate the window object when I am done? If not, why do I not have to? Below is a sample of my code...

#include <gtkmm.h>
#include "MattWindow.h"

#include <iostream>

using namespace std;

void buttonpush();

int main(int argc, char* argv[])
{
    //This line initializes the GTK+ system
    Gtk::Main kit(argc,argv);

    //Declare a pointer to a window
    Gtk::Window* window = 0;

    try
    {
        //Load the glade file
        Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file("layout.glade");

        Assign window to point to the window object
        builder->get_widget("window1",window);
        window->show();
    }
    catch(Gtk::BuilderError& e)
    {
        cout<<e.what();
    }

    //Start everything up
    Gtk::Main::run();



    //Who destroys the object that window is currently pointing to?

    return 0;
}

void buttonpush()
{

}

Solution

  • From the GTK+ reference manual:

    A GtkBuilder holds a reference to all objects that it has constructed and drops these references when it is finalized. This finalization can cause the destruction of non-widget objects or widgets which are not contained in a toplevel window. For toplevel windows constructed by a builder, it is the responsibility of the user to call gtk_widget_destroy() to get rid of them and all the widgets they contain.

    The functions gtk_builder_get_object() and gtk_builder_get_objects() can be used to access the widgets in the interface by the names assigned to them inside the UI description. Toplevel windows returned by these functions will stay around until the user explicitly destroys them with gtk_widget_destroy(). Other widgets will either be part of a larger hierarchy constructed by the builder (in which case you should not have to worry about their lifecycle), or without a parent, in which case they have to be added to some container to make use of them. Non-widget objects need to be reffed with g_object_ref() to keep them beyond the lifespan of the builder.

    To answer your question: yes, you should manually destroy the window when you're done with it.