|
Boost : |
From: Joe Gottman (joegottman_at_[hidden])
Date: 2002-02-08 23:26:18
----- Original Message -----
From: "Greg Colvin" <gcolvin_at_[hidden]>
To: <boost_at_[hidden]>
Sent: Friday, February 08, 2002 10:11 PM
Subject: Re: [boost] Usefulness of weak_ptr
> > I just downloaded weak_ptr, and I was wondering how useful it is.
What
> > can you do with a weak_ptr<T> that you can't do with a plain T*?
>
> One common use is to keep a cache of shared objects. The cache can
> be implemented as a container of weak_ptr, so that just being in
> the cache doesn't prevent an object from being deleted when the last
> shared_ptr to the object goes away.
>
I can see this, but there seem to be a few dangers. For instance, it
would be very dangerous to keep a set of weak_ptr's. If the underlying
object of a weak_ptr were deleted, then the weak_ptr's get() suddenly
returns a 0. This will almost certainly mess up the set's invariant that
its members are stored in some sorted order.
Also, I think weak_ptr is inherently thread-unsafe. For instance, its
get() function is implemented as follows:
T * get() const // never throws
{
return use_count() == 0? 0: px;
}
Consider the following code:
weak_ptr<int> pWeak;
int *pInt = pWeak.get();
If the shared_ptr underlying pWeak goes out of scope between when
use_count() returns 1 and px is returned then get() could still return a
pointer to an object that has been deleted.
Joe Gottman
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk