Boost logo

Boost Users :

Subject: Re: [Boost-users] seeking comments on 'weak_key_map' experiments
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2008-12-11 13:24:16


AMDG

Nicolas Lelong wrote:
> I've been doing too much Python recently - thanks to boost.python -
> and my return in the c++ world in quite painful. To help me manage
> some of my objects lifetime dependencies, I wanted an access to a
> system similar to the Python WeakKeyDictionary class :
>
> Mapping class that references keys weakly. Entries in the
> dictionary will be discarded when there is no longer a strong
> reference to the key. This can be used to associate additional
> data with an object owned by other parts of an application without
> adding attributes to those objects.
>
>
> I drafted a small 'weak_key_map' class based on boost weak_ptr,
> shared_ptr deleters, and a base class enabling classes to be used as
> keys in the weak_key_map.
>
> A small use case example is shown after, and source of weak_key_map &
> co are attached.
>
> I was wandering if someone had experience to share about a similar
> system ?
>
> For a first draft, it already serves me well - but, I'm not very happy
> with to "pollute" keys with the base class 'enable_master_ptr'...
>
> Any idea to improve all this ?

Is there some way that this can interface with
boost::shared_ptr/weak_ptr better?

weak_key_map<int, int> m;
boost::shared_ptr<int> k(new int(1));
m.insert(std::make_pair(k,5));

assert(*m.find(k) == 5);

k.reset();

assert(m.empty());

I rather suspect that the data structure would need to be implemented from
scratch. One of the nastier problems is how to deal with the case of:
iterator invalidation. The safest solution is to make the presence of an
iterator to a particular element guarantee that the key continues to exist.

struct node {
    boost::weak_ptr<K> key;
    V value;
    node* parent;
    node* left;
    node* right;
};

struct iterator {
    boost::shared_ptr<K> key; // force the key to stay alive
    node* pos;
};

In Christ,
Steven Watanabe


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net