Boost logo

Boost Users :

Subject: Re: [Boost-users] [smart_ptr] weak_ptr pointer semantics
From: Peter Dimov (pdimov_at_[hidden])
Date: 2011-11-11 15:14:02


Szymon Gatner wrote:

> On the second thought on weak_ptr's rationale with regards of
> thread-safety, what about this:
>
> if (!weak.expired())
> {
> // here it can expire from other thread
> weak.lock()->thisWillCauseAssert();
> }
>
> Isn't this how weak_ptr<> is suppose to be used?

No, it isn't.

if( shared_ptr<> p = weak.lock() )
{
    p->thisWillNotAssert();
}

expired() should only be used for positive tests: if( weak.expired() ). Once
a weak_ptr expires, it stays expired, so there is no potential for a race.


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