g_object_new 应该有匹配的 g_object_unref 吗?
我正在使用libnotify在我的应用程序中显示桌面通知; notify_notification_new()
返回一个 NotifyNotification*
,它应该作为第一个参数传递给通知库的进一步函数调用。
没有 notify_notification_free()
可以释放它返回的指针。我查找了 notify_notification_new()
的源代码,它在内部执行了 g_object_new()
,获取 GObject* 并将其作为 返回>NotfiyNotification*
,所以当我的应用程序进行清理时,我应该在 notify_notification_new()
返回的指针上调用 g_object_unref()
吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,除非引用是“浮动的”。
GInitiallyUnowned
的子类使用浮动引用;最常见的用途是 GTK 小部件。当您使用 gtk_whatever_new() 函数创建 GTK 小部件时,它有一个标记为浮动的引用。当您将小部件添加到容器时,容器还必须保存对该小部件的引用。但它不是在小部件上调用
g_object_ref()
并将引用计数增加到 2,而是“下沉”对象的浮动引用并将其转换为普通引用。您可以说容器现在“拥有”该小部件。然后,当您销毁容器时,它会对小部件调用
g_object_unref()
,引用计数变为零,并且小部件被销毁。这样你就不用再为自己毁坏它负责了。因此,对于通常不进入容器的普通 GObject,不存在所有权转移。当你使用完它们后,你必须自己取消引用它们。
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 callingg_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.答案是肯定的,我从Gnome关于所有权的页面中弄清楚了,我希望如此稍后帮助某人。
The answer is yes, I figured it out from Gnome's page on ownership, I hope it helps someone later.