Boost logo

Boost Users :

From: Ovanes Markarian (om_boost_at_[hidden])
Date: 2006-08-18 13:22:15


Scott,

In the described case I would bet, that the weak pointer is never reset to NULL, since you copy
pointer and not pointer by reference or pointer to pointer....

So if you are going to check if weak pointer is valid, it will be always valid, since copied by
value nothing will reset it to NULL. weak_ptr has for example bool expired()const member function,
but I think it could also be an operator bool()const function which reports the pointer validity.
So the first issue would be the checking of pointer validity.

On the other hand you can produce a valid shared_ptr out of weak_ptr, by calling the lock member,
since weak_ptr shares the reference counter with shared_ptr but does not increase it. Even if you
are in a cycle, some call to a data structure member might wish to ensure, that an object which is
pointed to by weak_ptr will not expire until the call is finished. So this call should call
weak_ptr::lock member and receive for the scope of call valid shared_ptr.

With Kind Regards,

Ovanes Markarian

On Fri, August 18, 2006 19:04, Scott Meyers wrote:
> I've recently realized that I just don't get something. Cycles of shared_ptrs
> are bad, because they can lead to resource leaks. To break a cycle, we're
> encouraged to use weak_ptrs. Okay, but we could use raw pointers to break the
> cycle, too, and I can't see any advantage offered by the weak_ptr. If A uses a
> shared_ptr to B and B uses a weak_ptr to A, B's life will be shorter than A's
> (its destructor will be invoked from A's destructor and will run to completion
> before A's does), so there is no advantage to a weak_ptr being able to tell if
> it dangles. In this context, it never will. So it seems that using a raw
> pointer to break cycles has no disadvantage over a weak_ptr, and it's more
> efficient (i.e., smaller and faster). Clearly, I'm missing something. Can
> somebody please explain what it is?
>
> I understand that weak_ptrs have other uses (e.g., as observers), so my question
> is only about the advice to use weak_ptrs to break cycles.
>
> Thanks,
>
> Scott
>
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>


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