Search code examples
gtk

Data ownership in GTK


In almost every page of the Gtk documentation there are the following phrases:

  • The data is owned by the caller of the function.
  • The data is owned by the called function.
  • The data is owned by the instance.

What do they mean, and what is the implication for memory management (g_free or g_object_unref)?

(I've read Introduction to Memory Management in GTK+, but it doesn't seem to cover "owned by the instance".)


Solution

  • You should read this like so:

    • the data: The parameter, the returned value, etc.
    • is owned by X: X is responsible to clean up (in most cases, this means calling g_object_unref on the data) the data.

    With this in in mind:

    1. The data is owned by the caller of the function: The 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. Notice that the caller of gtk_application_window_new, here main (through activate) is managing the reference count: it is calling g_object_unref on app.

    2. The data is owned by the called function: The 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: window is created by gtk_application_window_new but is never explicitly freeed. This id because the called function (here gtk_application_window_new) is taking care of this.

    3. The data is owned by the instance: The 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 here: The builder object is managed, but now the widgets returned by calls to gtk_builder_get_object. Even if written in C, GTK is object oriented. This means that instance, here, means the same as a class instance in most OO language.