GTK 中的数据所有权

Data ownership in GTK

几乎在Gtk文档的每一页中都有以下短语:

它们是什么意思,对内存管理有什么影响(g_freeg_object_unref)?

(我读过Introduction to Memory Management in GTK+,但它似乎没有涵盖“实例拥有”。)

您应该这样阅读:

  • 数据:参数,返回值等
  • 归X所有:X负责清理(在大多数情况下,这意味着对数据调用g_object_unref)数据。

考虑到这一点:

  1. 数据归函数调用者所有: gtk_application_window_new function works this way (as far as the application parameter is concerned). This means that memory management (i.e g_object_unrefing application) is to be done by the caller of gtk_application_window_new. See this example here。请注意 gtk_application_window_new 的调用者,此处 main(通过 activate)正在管理引用计数:它在 app.[=35= 上调用 g_object_unref ]

  2. 数据归调用函数所有: gtk_application_window_new function works this way (as the returned value is concerned). This means that memory management of the returned GtkWidget instance is to be done by gtk_application_window_new itself. So no need to call g_object_unref yourself. See this example here: windowgtk_application_window_new 创建,但从未 明确地 free 编辑。这个 id 因为 called 函数(这里 gtk_application_window_new)正在处理这个。

  3. 数据归实例所有: gtk_builder_get_object works this way (as far as the returned value is concerned). This means that the memory management of the GObject* returned is to be performed by the builder instance itself. Because of this, calling g_object_unref is not wanted. See this example herebuilder 对象被管理,但现在通过调用 gtk_builder_get_object 返回的小部件。即使用 C 编写,GTK 也是面向对象的。这意味着 instance,在这里,与大多数 OO 语言中的 class instance 相同。