Boost logo

Boost :

From: David Abrahams (abrahams_at_[hidden])
Date: 2000-12-17 09:18:30


----- Original Message -----
From: <radelber_at_[hidden]>

> Forgive me if this is the wrong place. I have a question concerning
> implementation rather than semantics.
>
> I have a need for a simple database that stores one copy of an
> object. If an object being inserted already exists, a pointer to it
> is returned. If the use_count drops to zero the object should be
> deleted.
>
> I'm thinking of using a set of shared_ptr. Is this a good solution?

Sounds appropriate. Realize, though, that the use_count won't drop to zero
until you remove the last shared_ptr to the element from the set.

> I have a class, myEvent
> typedef shared_ptr < myEvent > EventPtr;
> typedef EventPtr::iterator EventIter;
>
> set<EventPtr> EventDb; // my database
>
> MyEvent* pQuery = new MyEvent(...) // create new entry
> EventPtr cp(pQuery) // create shared_ptr
> // insert the object
> pair<EventIter, bool> pair1 = EventDb.insert(cp);
> cp = *pair1.first;
>
> 1. Is this correct? Reguardless of pair1.second, the original value
> of cp (pQuery) is destroyed and cp points to either the newly
> inserted (pQuery), or a previous shared_ptr.

In this case, it will never point to a previous shared_ptr, because a
shared_ptr to new memory will never compare equal to a
previously-initialized shared_ptr. I'm pretty sure you want a comparison
function on the set which compares the MyEvents which come from
dereferencing the EventPtrs. If you do that, then yes, you will get the
result you expect.

> 1b. Or if I reassign cp, does the inserted pQuery end up being
> destroyed?

The inserted pQuery is destroyed no matter what, since it is local to the
function you're executing. The MyEvent associated with pQuery will only be
destroyed if there was already an element in the set which matched according
to the set's comparison function.

> 2. How do I know when to delete the cp from the set? the shared_ptr
> will delete the object it points to, but do I have to check if
> use_count < 1?

Ah; sounds like you may want a weak_ptr, not a shared_ptr after all. A
weak_ptr "watches" and reacts to the deletion of an object, but doesn't hold
a counted reference, so it doesn't keep the object alive. Several have been
proposed but we don't have one in boost yet... sorry!

> 3. Does the constant creation of new objects and deletions at insert
> time cause memory fragmentation problems?

That depends a lot on your platform's memory subsystem, I guess.

-Dave


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk