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

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());

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.