Boost logo

Boost Users :

From: ethann.castell_at_[hidden]
Date: 2007-01-21 20:29:57


Typo on my part in this email. I've used enable_shared_from_this in my
real code.

Any other ideas?

The class you want to inherit from is "enabled_shared_from_this" not
"shared_from_this"

ethann.castell_at_[hidden] wrote:
>
> A big thanks to Phillip and Brian for their help so far. You've helped
> me increase my understanding of how shared_ptr's and
> enable_shared_from_this work.
>
> I've taken on board what you've both said but I still feel like I am
> missing something. I'm getting bad_weak_ptr exceptions (resulting in
> memory leaks) which make no sense to me. I've debugged through the
> code and checked the use_count and weak_count. The use_count looks ok
> but I'm not sure about the weak_count.
>
> I have a base class which contains the shared_from_this and a
> hierarchy of extended classes that inherit from the base class. The
> extended classes pass pointer's to themselves, to the other classes,
> so that linkages can be formed between them( at the base class level ).
>
> class base_class:: public shared_from_this
> prviate:
> boost::shared_ptr<base_class> m_Linked;
> // link to another base_class
>
> base_class::base_class( boost::shared_ptr<base_class> pLinked)
> {
> m_Linked = pLinked;
> // store link to other base class
> }
>
> class B : public base_class
> B::B(boost::shared_ptr<base_class> pLinked) : base_class( pLinked)
>
> class B1 : public B
> B1::B1(boost::shared_ptr<base_class> pLinked) : B( pLinked)
>
> class B2 : public B1
> B2::B2(boost::shared_ptr<base_class> pLinked) : B1( pLinked)
>
>
> class A : public base_class
>
> classA::Process()
> {
> boost::shared_ptr<A> ptr_a = shared_from_this();
> // get pointer to myself
>
> //afterwards - use_count = 2, weak_count = 2
> ...
> if (some_condition){
> boost::shared_ptr<B2> ptr_b2( ptr_a) ;
> // create new B2 and pass pointer to me.
> }else{
> // crashes with bad_weak_ptr error on this line.
> }
> }
>
> main()
> {
> boost::shared_ptr<A> ptr_a( new A() );
> ptr_a->process
> }
>
>
> It looks a little like ptr_a is being destroyed at the }else{
> statement (although I would have expected this at the end of Process().
> At the else statement ptr_a.use_count = 3, which I believe to be
correct.
>
> I've tried passing the boost pointers by value, by reference and also
> as constants but none of these make a difference.
>
> Any ideas?
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users

_______________________________________________
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