c++ - 在继承层次结构中使用 boost::shared_ptr

标签 c++ inheritance boost

想象一下下面的情况:

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

我想将警报附加到设备。 Alarm 和 Device 不允许相互了解(这最终会导致循环依赖)。所以这就是我使用接口(interface)类 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 来完成这项工作?

最佳答案

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

特别是这意味着您不能(成功地)在构造函数中调用 shared_from_this(),因为该对象刚刚被构造并且还不属于任何 shared_ptr 实例。

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

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

关于c++ - 在继承层次结构中使用 boost::shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1411279/

相关文章:

c++不同类的数组/列表

c# - 序列化继承 : Will an exception be thrown if the base class isn't marked [Serializable]?

OOP:实现具有更广泛签名的接口(interface)方法

c++ - 有没有办法让 Asio 在没有 Boost 的情况下工作?

c++ - boost::thread 构建错误(无法链接 lib && 未解析的外部)

C++:operator<< 嵌套类中的重载

c++ - int 在 operator== 中显示为 std::basic_ostream<char>

CSS不继承,而是使用默认

python - c++ boost python列表提取导致段错误

c++ - clang-format:如何对齐结构初始化列表