cmemory-managementgtk4

How do I free a GTK 4 widget in C?


I'm writing some C code where I have an elaborate algorithm for building GTK 4 widgets, and some of these widgets may end up "invalid" due to certain combinations of input data. However, I cannot always know this beforehand with how I've designed my application (and having a prior "validation" step would likely be more costly than a few extra allocations from invalid widgets), so sometimes I end up allocating a container widget that then goes unused because there are no children to add to it. In those cases, I would like to free that widget at the end of the function if I've determined that it is invalid. I tried searching for a solution to this and found the question Free object/widget in GTK 2?, but it's for GTK 2 and the one answer mentions using gtk_widget_destroy () which seems to have been removed between GTK 3 and GTK 4.

So, how do I free a GTK 4 widget in C?


Solution

  • To manually free a widget in GTK, you need to take ownership of it using g_object_ref_sink () as GtkWidget instances start out with a "floating" reference. After that, you can decide whether to parent it, and then use g_object_unref () to lower the reference count and potentially free it. Something like this:

    // Create the widget.
    GtkWidget *widget = some_widget_new ();
    
    // Take ownership, "sink" the floating reference.
    g_object_ref_sink (widget);
    
    // Check if widget setup was successful
    if (setup_widget (widget))
      // If it was, parent the widget.
      add_child (parent, widget);
    
    // Decrease the refcount
    g_object_unref (widget);