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
Remigiusz Zukowski wrote: [...]
boost::function
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
participants (2)
-
Peter Dimov
-
Remigiusz �ukowski