Re: [boost] weak_ptr, maybe empty -- doc bug?

Is this a documentation bug? template<class Y> explicit shared_ptr(weak_ptr<Y> const & r); Effects: If r is empty, constructs an empty shared_ptr ... It seems to be throwing an exception, rather than returning an empty shared_ptr.
-----Original Message----- From: boost-bounces@lists.boost.org [mailto:boost-bounces@lists.boost.org] On Behalf Of Joe Gottman Sent: Wednesday, August 03, 2005 7:16 PM To: boost@lists.boost.org Subject: Re: [boost] weak_ptr, maybe empty
"Andy Thomas-Cramer" <Andy_Thomas-Cramer@avid.com> wrote in message news:2F6133743473D04B8685415F8243F4765347D5@madison- msg1.global.avidww.com...
I have a weak_ptr that might be empty. If not empty, I'd like to
make a
smart pointer from it.
But the code below throws in the shared_ptr constructor, and I don't see how to test whether a weak_ptr is empty.
boost::weak_ptr<int> wp; boost::shared_ptr<int> sp(wp); if ( sp.get() ) { ... }
Suggestions?
It depends what you mean by empty. A weak_ptr can either a) be associated with a valid shared_ptr b) be associated with a shared_ptr that has since expired or c) be default initialized and never associated with a shared_ptr
If you don't need to differentiate between case b) and c), the most elegant way is if (shared_ptr<int> sp = wp.lock()) { //do work with valid shared_ptr }
If you need to distinguish between b) and c) you can continue with } else { weak_ptr empty; if (!(wp < empty) && !(empty < wp)) { //case c, default-constructed weak_ptr } else { //case b, expired weak_ptr } }
In practice, most people don't need to distinguish between case b) and c)
Joe Gottman
_______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
participants (1)
-
Andy Thomas-Cramer