Mau*_*aus 4 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;
}
};
Run Code Online (Sandbox Code Playgroud)
我想将警报连接到设备.警报和设备不允许彼此了解(这将最终呈现循环依赖性).这就是我使用Interface Class 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
Run Code Online (Sandbox Code Playgroud)
究竟是什么问题?在使用boost::shared_ptr引用和纯指针之前,此设置或多或少有效.是否有可能使这项工作boost:shared_ptr?
sth*_*sth 15
shared_from_this()只有在a拥有的动态分配对象上调用它时,调用才有效shared_ptr(请参阅文档中列出的要求).这意味着必须存在一个shared_ptr拥有该对象的东西,否则shared_from_this()将无法工作.
特别是这意味着你不能(成功地)shared_from_this()在构造函数中调用,因为对象只是被构造并且还没有被任何shared_ptr实例拥有.
要解决此问题,最好将附加警报的代码从构造函数移动到在完全构造对象后调用的单独方法:
boost::shared_ptr<Alarm> a(new Alarm());
a->attach(attachedDevice);
Run Code Online (Sandbox Code Playgroud)