Boost logo

Boost Users :

Subject: Re: [Boost-users] [smart_ptr] weak_ptr pointer semantics
From: Szymon Gatner (szymon.gatner_at_[hidden])
Date: 2011-11-11 14:50:44


2011/11/11 Tim Musson <Tim.Musson_at_[hidden]>:
> After re-reading your reply, I think your confusion comes from the following
> idea: "I still have weak_ptr<> which has a counter ".  A line from the
> weat_ptr<> documentation states that "When the last shared_ptr to the object
> goes away and the object is deleted, the attempt to obtain a shared_ptr from
> the weak_ptr instances that refer to the deleted object will fail". So,
> weak_ptr does not have a counter, that's it's weakness ;)

I don't think I am the one that is confused. When last shared_ptr<> goes out
of scope, weak_ptrs know that original object has expired - that is its purpose
and its strength not a weakness. It knows that it has expired (has
refcount == 0)
because it still has access to the counter. It knows it is zero, it knows object
has been deleted. Counter is not deleted as long as any weak_ptr<> exist
(weakcount > 0) otherwise every weak_ptr<> would be useless after last
shared_ptr<> been destroyed. To clarify: weak_ptr<> does not increase/decrease
refcount and does not affect object lifetime but it does affect
weakcount and counter's
lifetime.

> I assume that
> clears things up for you.

ditto

Security concerns make little sense for me. Calling get() to obtain raw pointer
is as dangerous with weak_ptr<> as with any other smart pointer. Moreover,
auto/scoped/unique_ptr can be reset() (or moved) from other thread and screw
things up as easily and no one complains. 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?

/Simon


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