Should a g_object_new have a matching g_object_unref?
Asked Answered
N

2

7

I'm using libnotify to show desktop notifications in my application; notify_notification_new() returns a NotifyNotification*, which should be passed as the first param to further function calls of the notification library.

There is no notify_notification_free() which frees the pointer it returns. I looked up the source of notify_notification_new() and internally it does a g_object_new(), gets a GObject* and returns it as a NotfiyNotification*, so when my application does the clean up, should I call a g_object_unref() on the pointer returned by notify_notification_new()?

Naoise answered 17/5, 2010 at 10:30 Comment(0)
S
13

Yes, unless the reference is "floating". Subclasses of GInitiallyUnowned use floating references; the most common use is GTK widgets.

When you create a GTK widget using a gtk_whatever_new() function, it has one reference which is marked as floating. When you add the widget to a container, the container must also hold a reference to the widget. But instead of calling g_object_ref() on the widget and increasing the reference count to 2, it "sinks" the object's floating reference and turns it into a normal reference. You could say that the container now "owns" the widget.

Then when you destroy the container, it calls g_object_unref() on the widget, and the reference count becomes zero, and the widget is destroyed. That way you're not responsible for destroying it yourself anymore.

So with normal GObjects, which usually don't go into containers, there is no transfer of ownership. You have to unreference them yourself when you're done with them.

Spirograph answered 17/5, 2010 at 13:29 Comment(5)
@Spirograph what additional headers do I need to call g_object_unref()? I'm currently including only libnotify/notify.h.Kea
#include <gobject/gobject.h>Spirograph
@ptomato, why do they use g_object_unref(model) on a GTreeModel here. Is it a bug in their code then?Chickaree
They are adding the model into a GtkTreeView. Or is it the fact that GtkTreeView isn't a GtkContainer why they must call g_object_unref?Chickaree
GtkTreeModel isn't a subclass of GInitiallyUnowned (see the first paragraph above) so it doesn't have floating references.Spirograph
N
3

The answer is yes, I figured it out from Gnome's page on ownership, I hope it helps someone later.

Naoise answered 17/5, 2010 at 10:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.