Boost logo

Boost Users :

Subject: Re: [Boost-users] Problem with weak_ptr exception
From: Stefan Strasser (strasser_at_[hidden])
Date: 2009-10-28 10:56:06


I can't make sense of your code ("weakThis" in both A and B, even though B is
derived from A?), but have a look at boost::shared_from_this

Am Wednesday 28 October 2009 12:43:08 schrieb Jacob Carlborg:
> I'm having some problems with bad_weak_ptr exceptions. I have reduced my
> code into this test case:
>
> #include <boost/shared_ptr.hpp>
> #include <boost/weak_ptr.hpp>
>
> using boost::shared_ptr;
> using boost::weak_ptr;
>
> class A
> {
> weak_ptr<A> weakThis;
>
> public:
> virtual ~A(){}
>
> shared_ptr<A> a;
>
> shared_ptr<A> getThis ()
> {
> shared_ptr<A> x(weakThis);
> return x;
> }
>
> void init ()
> {
> a = getThis();
> }
>
> static shared_ptr<A> create ()
> {
> shared_ptr<A> x(new A);
>
> x->weakThis = x;
> x->init();
>
> return x;
> }
> };
>
> class B : public A
> {
> weak_ptr<B> weakThis;
> public:
> virtual ~B(){}
>
> shared_ptr<B> getThis ()
> {
> shared_ptr<B> b(weakThis);
> return b;
> }
>
> static shared_ptr<B> create ()
> {
> shared_ptr<B> x(new B);
> x->weakThis = x;
> x->init();
>
> return x;
> }
> };
>
> int main (char** argv, int argc)
> {
> shared_ptr<B> b = B::create();
>
> return 0;
> }
>
> If I create an instance of A instead of B or doesn't call x->init() in
> the B's create function I don't get an exception. The problem is
> creating a shared_ptr from the weak_ptr in getThis.
>
> _______________________________________________
> 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