Re: Error in tr1::weak_ptr design.
John Nagle wrote:
Some related weak pointer questions:
1. I think I'm looking at an old version of TR1. Was weak_ptr::use_count
deleted from TR1?
I believe that weak_ptr::use_count was/is present in all versions of
TR1
4. Is "lock" thread-safe? That is, are you guaranteed that if you
do a "lock", and you get a valid shared_ptr, the object wasn't
deleted during the "lock"? If shared_ptr is intended to be
thread-safe, so should be "lock".
Yes, lock is thread-safe.
2. What's the rationale for not providing "operator->"? One
should be able to dereference a weak pointer directly, with
an exception if the weak pointer has expired.
T* operator-> is not present for the same reason T* get() isn't
present; there is no way to guarantee that the returned pointer is
valid.
In principle, one can solve that by providing
shared_ptr<T> operator-> () const;
but it only encourages subtle mistakes:
wp->f();
wp->g();
The programmer probably expects for f() and g() to be either both
executed or not; an exception from the second operator-> would be
sufficiently rare as to not show up on most tests. This is effectively
a race condition similar to
lock
f()
unlock
lock
g()
unlock
whereas the correct sequence is
lock
f()
g()
unlock
or, in weak_ptr speak,
if( shared_ptr<T> pt = wp.lock() )
{
pt->f();
pt->g();
}
else
{
// handle expiration
}
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]