0

please can anyone explain the reason for the following behavior

#include <iostream>
#include <boost/enable_shared_from_this.hpp>

using namespace std;


class A;
  typedef boost::shared_ptr<A> A_sptr_t;

  class B;
    typedef boost::shared_ptr<B> B_sptr_t;

    class A : public boost::enable_shared_from_this<A> 
    {
      public:
      A() {}
      virtual ~A() {}
    };



class B : public A, public boost::enable_shared_from_this<B>  
{
  public:
  B() {}
  virtual ~B() {}

  void f(void) 
  {
    cout << "this is working " << boost::enable_shared_from_this<B>::shared_from_this() << endl;
  }

};


int main() 
{
  B_sptr_t b(new B());
  b->f();
  return 0;
}

the program will be terminated with the following message

terminate called after throwing an instance of 'boost::bad_weak_ptr'
  what():  boost::bad_weak_ptr
Aborted

Edited by Reverend Jim: Fixed formatting

1
Contributor
1
Reply
2
Views
8 Years
Discussion Span
Last Post by rpjanaka
0

OK , I found the reason

problem is that we have two weak_ptrs -- one weak_ptr<A> and one weak_ptr<B> -- and only one of them will be initialized correctly when you create the smart pointer.

the solution is that we do not have to implement both A and B from the boost::enable_shared_from_this<>. Instead do it only for the class A and when needs to get a shared_ptr to class B do as follow.

dynamic_pointer_cast<B>(shared_from_this());

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.