Null shared pointer confusion

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

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@carlh.net> 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@lists.boost.org http://lists.boost.org/mailman/listinfo.cgi/boost-users
participants (2)
-
Carl Hetherington
-
Emil Dotchevski