Hello,

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 ?

Best regards,
Nicolas.

  int Master_count = 0;

  class Master : public mgd::enable_master_ptr<Master>
  {
  public:
    Master() { Master_count++; }
    ~Master() { Master_count--; }
  };

  int Dependent_count = 0;

  class Dependent : boost::noncopyable
  {
  public:
    Dependent() { Dependent_count++; }
    ~Dependent() { Dependent_count--; }
  };

BOOST_AUTO_TEST_CASE( test_weak_key_map_lifeTime )
{
  typedef boost::shared_ptr<Dependent> value_t;
  typedef mgd::weak_key_map<Master, value_t> map_t;
  map_t map;

  {
    Master master1;

    BOOST_CHECK( !map[&master1] );

    map[&master1] = value_t( new Dependent );

    BOOST_CHECK( map[&master1] );

    {
      Master master2;
      map[&master2] = value_t( new Dependent );

      BOOST_REQUIRE_EQUAL( Master_count, 2 );
      BOOST_REQUIRE_EQUAL( Dependent_count, 2 );
    }

    map[&master1] = value_t( new Dependent );

    BOOST_REQUIRE_EQUAL( Master_count, 1 );
    BOOST_REQUIRE_EQUAL( Dependent_count, 1 );

    map.clear();

    BOOST_REQUIRE_EQUAL( Master_count, 1 );
    BOOST_REQUIRE_EQUAL( Dependent_count, 0 );
  }

  BOOST_REQUIRE_EQUAL( Master_count, 0 );
  BOOST_REQUIRE_EQUAL( Dependent_count, 0 );
}