I'm having trouble with a bad weak_ptr exception when I try to pass a shared_from_this() from a derived class that inherits from the callback interface into a third class which takes the callback base class shared_ptr in the constructor. Why doesn't this work? See simplified test case below:
#include <boost/tr1/memory.hpp>
class MyCallbacks : public std::tr1::enable_shared_from_this<MyCallbacks>
{
public:
virtual ~MyCallbacks() {}
virtual void callback1() = 0;
};
class Worker
{
public:
Worker(std::tr1::shared_ptr<MyCallbacks> cb) : callbacks(cb) {}
void do_work() { if (callbacks) callbacks->callback1(); }
private:
std::tr1::shared_ptr<MyCallbacks> callbacks;
};
class Boss : public MyCallbacks
{
public:
Boss() : worker(shared_from_this()) {}
void go()
{
std::cerr << "Calling worker->do_work" << std::endl;
worker.do_work();
}
void callback1()
{
std::cerr << "callback1" << std::endl;
}
private:
Worker worker;
};
int main (int argc, char const *argv[])
{
std::tr1::shared_ptr<Boss> boss(new Boss);
boss->go();
return 0;
}
shared_from_this() cannot be called in the constructor because at least one shared_ptr must exist first see the Requires statement at the bottom of this page