[英]Using boost::shared_ptr within inheritance hierarchy
想象一下以下情況:
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;
}
};
我想將警報連接到設備。 警報和設備不允許彼此了解(這將最終呈現循環依賴性)。 這就是我使用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
究竟是什么問題? 在將boost::shared_ptr
與引用和純指針一起使用之前,這種設置或多或少有效。 是否可以使用boost:shared_ptr
來完成這項工作?
對shared_from_this()
的調用僅在由shared_ptr
擁有的動態分配對象上調用時才有效(請參閱文檔中列出的要求)。 這意味着必須存在擁有該對象的shared_ptr
,否則shared_from_this()
將不起作用。
特別是這意味着你不能(成功地)在構造函數中調用shared_from_this()
,因為對象剛剛被構造並且還沒有被任何shared_ptr
實例擁有。
要解決此問題,最好將附加警報的代碼從構造函數移動到在完全構造對象后調用的單獨方法:
boost::shared_ptr<Alarm> a(new Alarm());
a->attach(attachedDevice);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.