Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a g_object_new have a matching g_object_unref?

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()?

like image 727
legends2k Avatar asked May 17 '10 10:05

legends2k


2 Answers

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.

like image 183
ptomato Avatar answered Sep 18 '22 17:09

ptomato


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

like image 31
legends2k Avatar answered Sep 19 '22 17:09

legends2k