[webkit-dev] We need OwnPtrHashMap

Geoffrey Garen ggaren at apple.com
Wed Aug 25 13:46:00 PDT 2010

> Sorry for the late-night webkit-dev spam, but in deploying adoptPtr,
> I've noticed a number of places where have a HashMap that owns its
> values as OwnPtrs.  Unfortunately, this very clumsy currently.  Each
> instance of this pattern has its own way of hacking around the
> problem, which might or might not result in memory errors.  We really
> should have an OwnPtrHashMap (to complement RefPtrHashMap) that
> understands how to handle this case correctly.

To clarify:

Optimization aside, HashMap<RefPtr<T>, U> and HashMap<T, RefPtr<U> > work just fine. RefPtrHashMap was an optimization. The feature it needed, which HashMap did not provide, was the ability to look up a value by a non-key type (raw pointer), without first converting to key type (RefPtr), since converting to RefPtr would cause refcount churn. We couldn't find a way to do this using HashTraits without using casts that violated strict aliasing rules.

In contrast, HashMap<OwnPtr<T>, U> and HashMap<T, OwnPtr<U> > don't work at all. They don't compile, since OwnPtr is not copyable. If you made OwnPtr copyable, they would accidentally delete items during get() and resize() operations.

A HashMap that owns its values wants to do something special when an item is overwritten, removed, or implicitly removed by HashMap destruction, but it doesn't want to do anything special when an item is copied or extracted.

I think the best way to achieve this with HashMap might be a hash trait, rather than literally putting an OwnPtr in the map. Specifically, the trait would be one willRemove callback, which took an iterator to an item, and one willRemoveAll callback, which took a begin iterator. These callbacks would default to empty inline functions.

But maybe there's a way to use special hash traits and translators to eliminate all or nearly all the C++ copying operations.


More information about the webkit-dev mailing list