
hello, Callback mechanism defined by boost::function and by means boost::bind instead of using callback virtual class is very comfortable, but has one big shortcoming: using callback class, passing object can be stored as weak_ptr and if weak_ptr is invalid the callback can be automatically unregistered. I've tried to implement such behaviour with boost::function and boost::bind with some helper class holding weak_ptr: template<typename T> class my_wptr { boost::weak_ptr<T> m_wptr; constructors etc... }; and two helper functions: template<typename T> T* get_pointer( my_wptr &_wptr ) { boost::shared_ptr<T> sptr = _wptr.m_wptr.lock(); if( !sptr ) throw some_exception; return _wptr.get(); } and template<typename T> my_wptr<T> wptr_from( boost::weak_ptr<T> &_sptr ) { return my_wptr( _sptr ); } now I can use standard shared_ptr version: boost::function<void()> f1 = boost::bind( &class::method, some_shared_ptr ); or my version holding weak_ptr: boost::function<void()> f2 = boost::bind( &class::method, wptr_from( some_weak_ptr )); This works, but is unsafe - after get_pointer succesfully returns pointer to the object, the object is unlocked and can be deleted during class::method execution. Can anyone help me solving this problem ? regards Remigiusz Zukowski, Poland --------------------- Panorama Internetu - prognoza pogody, poczta e-mail z największym załącznikiem, SMS, wyszukiwarki: Gooru, Anonser, serwisy: randki, ogłoszenia, wakacje, program TV, Kina, muzyka, DVD, newsy, inne. http://www.panoramainternetu.pl/ (http://www.epf.pl/)

Remigiusz Zukowski wrote: [...]
boost::function<void()> f2 = boost::bind( &class::method, wptr_from( some_weak_ptr ));
This works, but is unsafe - after get_pointer succesfully returns pointer to the object, the object is unlocked and can be deleted during class::method execution. Can anyone help me solving this problem ?
You can use template<class T> shared_ptr<T> sptr_from( weak_ptr<T> const & wpt ) { return shared_ptr<T>( wpt ); // throws on wpt.expired() } and then boost::function<void()> f2 = boost::bind( &class::method, boost::bind( &sptr_from<class>, some_weak_ptr ) ); It's a bit more typing, though.
participants (2)
-
Peter Dimov
-
Remigiusz �ukowski