|
Boost Users : |
Subject: [Boost-users] seeking comments on 'weak_key_map' experiments
From: Nicolas Lelong (rotoglup_at_[hidden])
Date: 2008-12-11 10:09:10
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 );
}
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