Gtk_css_provider_new and g_object_unref

Hi

Have I to use g_object_unref after I worked with gtk_css_provider_new to change Widget-Colors ?

The documentation says nothing about it.

Each constructor returns a full reference[1] and unless there’s an ownership transfer somewhere, you’re responsible for releasing that reference if you want to free the resources associated to the instance.

In this particular case, assuming you’re calling gtk_style_context_add_provider_for_display(), the GtkCssProvider instance is still owned by you, and the function acquires a reference on the style provider. You will have to call g_object_unref() to release the reference you own.

For more information, I recommend you read the section on reference counting of the type system documentation.


  1. Except for types that inherit from GInitiallyUnowned, in which case you’ll get a floating reference that something will have to sink, unless the type itself sinks it, like GtkWindow does; but that’s something that the API reference will tell you. ↩︎

Thank you. So, can I use as a “rule of thumb”, that everytime a object is involved, i have to use g_object_unref after the job is done ?

As I said, it depends; some API involve a full ownership transfer. For instance, this does not require you to release the reference from the constructor:

GtkEventController *controller = gtk_gesture_click_new ();
// ...
gtk_widget_add_controller (widget, controller);

Because gtk_widget_add_controller() takes ownership of the event controller, and is responsible for freeing it. On the other hand, this code:

GIcon *icon = create_icon_from_somewhere ();

gtk_entry_set_icon_from_gicon (entry, GTK_ENTRY_ICON_PRIMARY, gicon);
g_object_unref (icon);

requires calling g_object_unref() on the GIcon instance, because gtk_entry_set_icon_from_gicon() does not fully transfer the ownership of the argument to the callee, and leaves the ownership to the caller.

Basically: you’re supposed to release all the references you own. If you don’t own any reference, then you don’t have to release anything.

The reason for my question is, that the documentation is sometimes not detailed enough. As example this one: “GtkCssProvider is an object implementing the GtkStyleProvider interface.”

The necessity for g_object_unref() is not mentioned.

You have to understand object orientation, and specifically OOP with C/GObject. GtkCssProvider inherits from GObject, and implements the GtkStyleProvider interface. You can see it in the documentation.

1 Like