From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-02-11 10:28:34


From: "bill_kempf" <williamkempf_at_[hidden]>
> I'm unconvinced that weak_ptr<> is useful in a MT program.

Who's trying to convince you otherwise? ;-)

> At least
> not if ANY of the pointers (shared_ptr<> or weak_ptr<>) are shared
> across thread boundaries.

More precisely, not if the last shared_ptr that owns the object may be
destroyed by a different thread.

Shared and weak pointers are typically not shared between threads; usually a
copy is passed to the other thread.

Still, a weak pointer can be used safely in a multithreaded program when (a)
the object is owned by the same thread, i.e. there exists at least one
shared_ptr that is guaranteed to be destroyed by the current thread, or (b)
when the user locks appropriately.

> A redesign might help. If the weak_ptr<>'s only functionality was
> conversion to a shared_ptr<> where you'd get a NULL shared_ptr<> if
> the object were gone, you wouldn't have the above problem. However,
> it wouldn't be efficient either (and would be danged difficult to
> implement).

The usual choice. Is the user responsible for synchronization, yielding
performance, or is the implementation, yielding safety (at a price that many
would find unbearable.)

Unfortunately there is no portable "check if zero, increment only if not
zero, return the previous value" atomic operation AFAIK.