The question about boost::shared_ptr here:
I have 3 classes.
A is some kind of main class that is responsible for everything.
B is a class that only has functions to do some work.
Dispatcher is just a class that wraps around a separate thread that receives work from the B instances executed on that thread.
So it works as follows: A has an instance of Dispatcher . Now, in case A , an instance of B is created and passed to the dispatcher.
The important part is that B needs to call A::callback() when this is done. This is why B gets a reference to constructor A in it (see code below)
A.hpp
class A : public boost::enable_shared_from_this<A> { public: A(); void sendB(); void callback(); private: Dispatcher m_Dispatcher; };
B.hpp
class B { public: B(boost::shared_ptr<A> ptr); boost::shared_ptr<A> m_PointerToA; };
Dispatcher.hpp
class Dispatcher { public: void run(); void dispatch(boost::shared_ptr<B> b); private: void doWork(); boost::thread m_Thread; };
a.cpp
A::A() { m_Dispatcher.run(); } void A::sendB() { boost::shared_ptr ptr_B; ptr_B.reset(new B(this->shared_from_this); m_Dispatcher.dispatch(ptr_B); }
B.cpp
B::B(boost::shared_ptr<A> ptr) : : m_PointerToA(ptr) { }
main_example.cpp
int main() { A instanceA; while(true) { instanceA.sendB(); } return 0; }
So my question is:
Is it possible to use boost :: shared_ptr for this purpose?
I'm not sure if this is shared_ptr right. My problem is that I do not know what happens when I call the constructor from B and pass the this pointer to this . Now according to shared_ptr I would suggest that m_PointerToA has ownership of A But that would mean that when Dispatcher was done and my instance of B was deleted, it would also delete the m_PointerToA link, which actually means that it kills the object itself, despite the fact that there is a real instance of A basically cycle.
Update:
The code has been added and the question itself has been updated to make it more understandable.