Search code examples
c++gtkmm3

Is it wise to not RefPtr all Gtk::Builder variables because Gtk::Application is referenced already


I'm still learning gtkmm3 so please be considerate with my (stupid) question

I created a sample gtkmm3 app, the main class starts with:

#include "app-window-declaration.h"

// signal activate function was here

int
main (int argc, char *argv[])
{
    Glib::RefPtr<Gtk::Application> app =
        Gtk::Application::create("io.gitlab.Keyikedalube.Sample-gtkmm");
    ...
}

And the implementation class app-window-declaration inherits Gtk::Window and uses three or more Gtk::Builder resources, all referenced with Glib::RefPtr because in chapter 26 the gtkmm docs explains that this must be done so

Gtk::Builder must be used via a Glib::RefPtr. Like all such classes, you need to use a create() method to instantiate it. For instance,

Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file("basic.glade");

However, (and here's my stupid question) since, in the main function the variable app is already referenced... won't the Builder variables automatically go out of scope and delete themselves when app does?


Solution

  • A Gtk::Builder must be used via a Glib::RefPtr. Period. End of discussion. When the documentation says that there is only one way to do things, then trying to do things another way is undefined behavior.

    The reason why this restriction exists is part of the black box. You are not allowed to assume it has something to do with going out of scope and deleting themselves. (That being said, one possible reason for this restriction might be so that the objects do not delete themselves when your variable goes out of scope. The factory might keep a copy of the pointer somewhere for future use.)