Re: Problem with references



On Fri, 14 Mar 2008 09:41:22 +0100 Gabriele Greco wrote:

After some headache with my gtk C++ classes I've found  with a small
test program this fact about the gobject references:

Sorry, not sure what you're trying to do.  Are you trying to do
something with gtkmm?  Or are you creating your own bindings?

Here is the code (tested with GTK 2.12):

#include <gtk/gtk.h>

int main()
{
    gtk_init(NULL, NULL);

    GtkWindow *w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    GtkWidget *l = gtk_label_new("Test");

    printf("Window\nStart: %d ", G_OBJECT(w)->ref_count);
    g_object_ref_sink(G_OBJECT(w));

Gtk owns all toplevel windows.  It already does _ref_sink() on
GtkWindows on creation (see gtk_window_init() in gtk/gtkwindow.c).  In
this case, if you want to keep an extra reference to 'w', you'd just
call g_object_ref() on it.

    printf("Sink: %d ", ((GObject *)w)->ref_count);
    g_object_unref(G_OBJECT(w));

This should be ok as well, IFF you've previously called g_object_ref()
and thus own a reference to it.  As I said, Gtk owns the initial
(non-floating) reference GtkWindow that you get back with
gtk_window_new().

    printf("End: %d\n", ((GObject *)w)->ref_count);

    printf("Label\nStart: %d ", G_OBJECT(l)->ref_count);
    g_object_ref_sink(G_OBJECT(l));
    printf("Sink: %d ", ((GObject *)l)->ref_count);
    g_object_unref(G_OBJECT(l));
    printf("End: %d\n", ((GObject *)l)->ref_count);
}

This more or less works (because non-window GtkObjects are created
floating), but that's usually not what you'd want to do.  Again you'd
probably want to just take a normal reference on the widget and then
unref it when you don't need it anymore.  When you add a widget to a
container, it will take care of ditching the floating reference and
taking a real reference.

        -brian



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]