Re: Reference counting advice needed



Jeff Franks <jcf tpg com au> writes:
> 
> I need some advice on reference counting. Is it right that when your
> using objects which derive from GObject, unlike GtkObject, its safe to
> use the object returned from gtk_x_new without calling gtk_x_ref. Only
> calling gtk_x_unref when your finished, e.g.  GtkStyle.
> 

When you create a GtkObject, you don't actually own a reference,
instead the object has a "floating" reference which keeps it
alive. Anyone at any time may remove that floating reference with
gtk_object_sink(). Most widget code assumes that only GtkContainer
will call sink() and that the container will call ref() to hold a
reference before sinking. So that means the parent container typically
holds the only reference to a child widget. GtkWindow gets a ref/sync
on creation, and is owned by GTK. The destroy signal requests that
reference owners drop references, so causes GtkContainer to drop refs
to widgets and causes GTK to drop references to toplevel GtkWindow,
normally leading to object finalization, unless someone else is
holding a reference.

GObject has no floating flag, so when you call _new() to create one,
you do own a reference and you must call unref() at some point.  Also,
there is no destroy signal, so no way to request that references held
by others be dropped.

Note that if you create a GtkObject and never pass it to an owner, you have to
sink it yourself, e.g.:
 foo = my_gtkobject_new ();
 gtk_object_sink (foo); /* correct, frees object */ 
vs.
 foo = my_gtkobject_new ();
 gtk_object_unref (foo); /* wrong! */ 

However, this code is fine:
 foo = my_gobject_new ();
 g_object_unref (foo); /* correct, frees object */

and it's a mem leak if you never call unref.

Havoc




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