Re: reffing/unreffing tutorial



DANIELLLANO wrote:
I've seen this and I think there should be a tutorial of the
reffing/unreffing thing. Not many people including me knows how
references should be taken care of.
Is there and easy tutorial of reffing/unreffing?
Is anyone willing to make one?

    Its really a quite simple concept as long as you dont
include gtk+ "floating references" which are there to simplify
the programmers work and utterly confuse the newbie ;-)

When you allocate memory using malloc(), you free it with free(),
when you instantiate a GObject, you release it with g_object_unref().
the difference is that you dont know if that object is "finalized" or
not (finalize is just a fancy way of saying that the object is freed
and all the resources it occupied are actually released).

Generaly, an object is created with a reference count of one, this means
that the piece of code responsable for instantiating the object "owns" it
(that reference "belongs" to the allocating code), other pieces of code
may depend on that objects existance for a finate amount of time, during that
time it will hold another reference to it.

Take signal emmission for example, the objects own code might look like
this:

if (signal condition) {
    g_object_ref(object);
    g_signal_emit(...); // call all interrested signal handlers
    g_object_unref(object);
}

What if the first signal handler is the "owning" entity and
decides for some reason to release the object, and that the second
signal handler down the chain gets called ? if there wasn't an
extra reference owned by the object itself, chances are the
second second signal handler would cause the program to segfault
(reference to some non-allocated memory space or something).

Anyhow, I think there is plenty of documentation on this subject
and it is inapropriate for a "tutorial", as reference counts are
more of an important detail to take into account than a task to
perform.

I hope I have enlightened you on this subject though ;-)

For more detailed documentation on the object system, you
should read: http://www.le-hacker.org/papers/gobject/index.html

Cheers,
                        -Tristan




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