【问题标题】:Using boost::shared_ptr within inheritance hierarchy在继承层次结构中使用 boost::shared_ptr
【发布时间】:2009-09-11 14:34:45
【问题描述】:

想象以下情况:

class IAlarm : public boost::enable_shared_from_this<IAlarm>  {
   boost::shared_ptr<IAlarm> getThisPointerForIAlarm() {
      return shared_from_this();
   }

   void verifyThis(int); // called by Device
};

class Alarm : public IAlarm {
   Alarm( boost::shared_ptr< Device >  attachedDevice){
      attachedDevice->attachAlarm(this->getThisPointerForIAlarm());
   }

   void sendAlarm(){
      attachedDevice->Alarm();
   } 

};

class Device {
   attachAlarm( boost::shared_ptr< IAlarm > ia){
      this->alarm=ia;
   }
};

我想将警报附加到设备。不允许警报和设备相互了解(这将导致循环依赖)。所以这就是我使用接口类 IAlarm 的原因。最后,我希望能够在一台设备上附加多个警报。警报可以访问它们所连接的设备,并且设备可以在附加的警报上开始验证

一切都编译得很好。但是,如果我尝试将警报附加到设备上,我会得到以下信息:

boost::shared_ptr<Device> ptrDevice(new Device());
boost::shared_ptr<IAlarm> ptrAlarm(new Alarm( ptrDevice ));

    terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_weak_ptr> >'

  what():  tr1::bad_weak_ptr

究竟是什么问题?在将 boost::shared_ptr 与引用和纯指针一起使用之前,此设置或多或少有效。是否可以使用boost:shared_ptr 完成这项工作?

【问题讨论】:

  • 您没有显示实际代码,因此很难说出任何相关信息。
  • @KayEss:我同意。这里缺少太多了。
  • 如何声明“警报”?为什么你使用 this->alarm 而不是简单的“alarm”?
  • 设备不应该来自 IAlarm。实际的代码要发布的太多了。但是给定的代码片段或多或少地反映了问题。警报声明如下: boost::shared_ptr ptrAlarm(new Alarm( ptrDevice )); this->alarm=xy 和 alarm=xy 有区别吗?

标签: c++ inheritance boost


【解决方案1】:

只有在 shared_ptr 拥有的动态分配对象上调用 shared_from_this() 时调用才有效(请参阅要求 listed in the docs)。这意味着必须存在拥有该对象的shared_ptr,否则shared_from_this() 将不起作用。

这尤其意味着您不能(成功)在构造函数中调用shared_from_this(),因为该对象刚刚被构造并且还没有被任何shared_ptr 实例所拥有。

要解决这个问题,您最好将附加警报的代码从构造函数移到一个单独的方法中,该方法在对象完全构造后被调用:

boost::shared_ptr<Alarm> a(new Alarm());
a->attach(attachedDevice);

【讨论】:

    猜你喜欢
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 2023-04-03
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多