Boost logo

Boost Users :

Subject: Re: [Boost-users] Null shared pointer confusion
From: Emil Dotchevski (emildotchevski_at_[hidden])
Date: 2009-07-08 21:04:38


To make an empty ("owns nothing") shared_ptr, you use shared_ptr's
default ctor; shared_ptr<A>((A *)0) creates a non-empty shared_ptr
which calls delete on the A pointer when all references expire (note
that passing a null pointer to delete is valid in C++.)

Emil Dotchevski
Reverge Studios, Inc.
http://www.revergestudios.com/reblog/index.php?n=ReCode

On Wed, Jul 8, 2009 at 4:23 PM, Carl Hetherington<lists_at_[hidden]> wrote:
>
> Hi,
>
> In the following program...
>
> #include <boost/shared_ptr.hpp>
> #include <boost/weak_ptr.hpp>
>
> class A {};
>
> int main ()
> {
>        boost::shared_ptr<A> x; // A: bad_weak_ptr thrown
> //      boost::shared_ptr<A> x ((A *) 0); // B: works
>
>        boost::weak_ptr<A> y (x);
>        boost::shared_ptr<A> z (y);
> }
>
> ... I observe that with line A included (but not line B), a bad_weak_ptr is
> thrown by the line which declares z.
>
> With line B included (but not line A), all is well.
>
>> From looking at the boost source, it seems that line A results in a
>
> shared_ptr to nothing (use_count() == 0), and line B results in a shared_ptr
> to 0 (use_count() == 1).
>
> I can work around this, I'm sure.  Can anyone clarify my muddled thinking
> and explain why boost is behaving correctly in this situation (if indeed it
> is!)
>
> Many thanks
>
> Carl
>
> _______________________________________________
> 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