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()
o开发者_JS百科n the pointer returned by notify_notification_new()
?
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 GObject
s, 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.
The answer is yes, I figured it out from Gnome's page on ownership, I hope it helps someone later.
精彩评论