为什么我不能将shared_from_this与回调接口对象一起使用?

时间:2011-12-16 01:33:38

标签: c++ boost shared-ptr smart-pointers

当我尝试将从回调接口继承的派生类中的shared_from_this()传递到第三个类时,我遇到了一个错误的weak_ptr异常,该第三个类在构造函数中获取了回调基类shared_ptr。为什么这不起作用?请参阅下面的简化测试用例:

#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;
}

1 个答案:

答案 0 :(得分:3)

在构造函数中无法调用shared_from_this(),因为至少有一个shared_ptr必须首先存在see the Requires statement at the bottom of this page