想象以下情况:
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
使其正常工作?