Re: widget with label (reference counts)

On Tue, Nov 12, 2002 at 04:29:18PM -0500, Tristan Van Berkom wrote:
      Thanks for the clarification;
do _all_ newly created GtkObjects start
with a floating reference and a reference count of 0 ?

GtkObjects start with a floating reference (which means a refcount of
1). A floating reference is a reference that no one owns (thus it's
floating). Anyone can remove the floating reference. However, no one
can ever own it.

To remove the floating reference, you call gtk_object_sink().

If you're expecting to be the "primary owner" of an object, 
you would do this:
 g_object_ref (object);    /* refcount is now 2, one floating one owned
                              by us */
 gtk_object_sink (object); /* refcount is now 1, owned by us */

That is what a container does. gtk_object_sink() does nothing if 
the object doesn't have a floating reference.

It is an error to remove a floating reference with g_object_unref(),
because the "floating" flag will still be set so someone else will
think the object still has a floating reference. You must use 

You have to ref the object before sinking it, in case the floating
reference is the last ref, which would result in finalizing the

Please correct me if I'm wrong:

- a GObject holds a "ref_count"
- a GtkObject holds a "floating" (flag or bool or something) (along with
GObject's ref_count)
- calling g_object_ref on a simple GObject will "ref_count++;"

Those are right.

- calling g_object_ref on a GtkObject type of GObject will "if
(++ref_count == 1) floating = FALSE;"

This is wrong, ref does not affect floating references.

- calling g_object_unref on a "floating" GtkObject will finalize

This can't happen, because if an object has _only_ the floating ref
you must use gtk_object_sink() not unref() to remove it; if it 
has other non-floating refs, you can use unref(), but the object won't
be finalized if it still has a floating ref.

- calling g_object_unref on a GtkObject with a ref_count of one will
finalize (of course)


- a GtkWindow usualy "floats" its entire lifespan

No, GTK itself does a ref/sink on the GtkWindow; the GtkWindow is
"owned" by the GTK runtime.

      Is this "floating" concept a new implementation or just
still around for legacy/compatability reasons ? If this is new;
what is the advantage of having a "floating state" along with 
a reference count ?

Without the floating state, you would have to write code like this:

 label = gtk_label_new ();
 button = gtk_button_new ();
 window = gtk_window_new ();
 gtk_container_add (button, label);
 gtk_container_add (window, button);

 /* here is the part we avoid with a floating ref concept */
 g_object_unref (label); 
 g_object_unref (button);

i.e. you'd have to unref every widget after passing it to its
container if you didn't have the floating reference.


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