g_object_new 应该有匹配的 g_object_unref 吗?

发布于 2024-09-02 10:54:59 字数 661 浏览 5 评论 0 原文

我正在使用libnotify在我的应用程序中显示桌面通知; notify_notification_new() 返回一个 NotifyNotification*,它应该作为第一个参数传递给通知库的进一步函数调用。

没有 notify_notification_free() 可以释放它返回的指针。我查找了 notify_notification_new() 的源代码,它在内部执行了 g_object_new(),获取 GObject* 并将其作为 返回>NotfiyNotification*,所以当我的应用程序进行清理时,我应该在 notify_notification_new() 返回的指针上调用 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()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月依秋水 2024-09-09 10:54:59

是的,除非引用是“浮动的”。 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 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.

枯叶蝶 2024-09-09 10:54:59

答案是肯定的,我从Gnome关于所有权的页面中弄清楚了,我希望如此稍后帮助某人。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文