Re: GHashTable improvements



Federico Mena Quintero <federico ximian com> writes:

> Owen Taylor <otaylor redhat com> writes:
> 
> > GHashTable* g_hash_table_new_full          (GHashFunc       hash_func,
> > 					    GEqualFunc      key_equal_func,
> > 					    GDestroyNotify  key_destroy_func,
> > 					    GDestroyNotify  value_destroy_func);
> [snip]
> >  - In the discussion earlier, there was some idea that g_hash_table_replace()
> >    wasn't necessary as long as g_hash_table_insert() called the destroy
> >    notify on the key function.
> >  
> >    The main argument for keeping g_hash_table_replace() then seems
> >    to be that you might have a case where key and value are
> >    associated:
> > 
> >     g_hash_table_insert (hash, entry->name, entry);
> >   
> >    I've done this fairly frequently in the past.
> > 
> 
> Isn't it better to have
> 
> 	typedef void (* GHashDestroyNotifyFunc) (gpointer key, gpointer value);
> 
> 	GHashTable *g_hash_table_new_full (GHashFunc hash_func,
> 					   GEqualFunc key_equal_func,
> 					   GHashDestroyNotifyFunc
> 					   destroy_notify_func);
> 
> That way if you have keys that are associated with the value, you can
> destroy both of them in whatever the right way might be.

The problem with this is the braindead behavior of g_hash_table_insert()
when replacing an existing value - it keeps the old key and the 
new value. I don't think you'd want to call your destroy_notify_func
with the new key and the old value...

And I think making g_hash_table_insert() do something different
when a destroy_notify_func was provided would be highly unwise.
 
> >  - Do we need g_hash_table_foreach_remove_no_notify() since
> >    we have remove_no_notify() and destroy_no_notify()?
> 
> Is foreach_remove() really useful?  Don't you usually just want a
> g_hash_table_clear[_no_notify]()?
> 
> Maybe it is a stupid question if people indeed use it; I just happen
> to use g_hash_table_foreach_remove() to clear hash tables :)

foreach_remove() is actually about the only sane way to remove a set
of entries matching a predicate from a hash table.

Since you can't call remove() from within a foreach, the other
alternative is to use foreach() to build a list of keys to
remove, then to walk through that list and call remove on
each member.

It's not needed all that often, but when you need it, it is
pretty useful.

Regards,
                                        Owen




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