Re: Floating references



On Tue, 2017-06-06 at 11:50 +0200, Stefan Salewski wrote:
Some years ago I read about floating references as described in 

https://developer.gnome.org/gobject/stable/gobject-The-Base-Object-Type.html

Of course that makes sense.

Newly created objects get ref count 1, but are floating. If they get
put into a container element, floating ref is converted to ordinary
ref, and ref count stays at 1.

First, note that this is _only_ for initially unowned objects, which
GtkWidgets and some others happen to be; and this is mostly convenience
to avoid having to type extra g_object_unref() lines in C code.

To be honest I dont feel like this approach really makes sense, I much
prefer the autorelease pool approach taken by NextStep's objective C
implementation, where the semantic of giving away ownership is
expressed by pushing an object onto the nearest autorelease pool on the
call stack; usually as a part of a return statement.

A new object is always on an autorelease pool, and if ownership is not
claimed by the time you exit the nearest autorelease pool stack frame,
it gets cleaned up automatically.

This way you generally communicate through a return statement whether

  A.) You are granting access to an object you retain ownership of

or

  B.) You are giving the object away through your return statement,
      by pushing it onto the nearest autorelease pool on the stack

However, floating refs are what we had with GtkObject and now that
these floating initially unowned things found their way into GObject,
theres not really any way to turn back the clock and change it.


But I was wondering, why for newly created objects ref count is not
just zero, so when the element is put into a container it is just
increased to one.

In a way, it already is.

Whether it is the actual ref_count that is zero, or whether there is
just a separate floating flag I think is quite immaterial; you need to
have some state to mark the floating object after g_object_new()
returns otherwise it is in an invalid state until the first call to
g_object_ref().

The fact that the count itself is 1, is mostly irrelevant.

Cheers,
    -Tristan



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