Re: glist manipulation and reference count



[Note that your question is probably more appropriate for gtk-app-devel-list or gtk-list; this list is for the development *of* glib/gtk itself, not about developing apps that *use* glib/gtk.]

On 05/14/2009 08:47 PM, walty wrote:

However, one thing that surprised me is that, when I do "g_list_append" or
"g_list_prepend", it does not automatically add the reference count of the
stored GObject (unlike objective-C).

GList is a generic container that you can put any kind of pointer into. It doesn't know about GObjects or reference counting. In fact libglib (where GList is implemented) doesn't even link to libgobject.

So do I need to explicitly add the reference count each time the GObject is
inserted? and reduce the reference count when the object is removed? That
seems quite cumbersome to me.

That depends on how you want to use it. If you can be sure no one else will destroy the object while you're using it in the list, then no, you don't.

I've used both glib/gobject and NSArray/NSDictionary/etc., and personally I don't find either approach to be better or worse. I rarely need to increase refcnts on GObjects when I store them in lists, but perhaps others have different use cases that do require this.

Or can I add some function pointer to generalize this? Is there some kind of
best practice on this?

If you add the objects in one shot, you can do something like this after you've added all objects:

g_list_foreach(list, (GFunc)g_object_ref, NULL);

Of course that iterates over the entire list, so it would be a bit slow on a large list. You can always ref the objects as you insert them, e.g.:

list = g_list_append(list, g_object_ref(obj));

Of course you have to do something similar with _unref() when you remove items from the list or destroy the list.

	-brian


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