Boost logo

Boost :

Subject: [boost] [Smart Ptr][Bind] Implementaion of Weak Callback Function "weak_fn"
From: Artyom (artyomtnk_at_[hidden])
Date: 2009-03-21 13:49:22


Hello,

Today boost::bind allows to use shared_ptr to ensure that
when the function is called the object exists:

shared_ptr<bar> bar_ptr;
function<void()> foo;

foo=bind(&bar::slot,bar_ptr)

Now even if we call bar_ptr.reset() the object is still owned by foo.
But in some cases this is not good enough. This may create cyclic
dependecies if A has shared_ptr to B and gives it a callback to A
cyclic dependecy is created, so sometimes it would be useful to
be able to provide weak bind function that is called iff the
object exists -- that uses weak_ptr insteas of shared one.

I has written a small draft of boost::weak_fn

  template<T>
  boost::weak_fn(void (T::*p)(...), weak_ptr<T> ptr)

That creates such callback, it can be used with boost::bind similary
to mem_fn:

class foo {
  void bar(int x);
};

Like:

function<void(int x,int y)> f2=bind(weak_fn(&foo::bar,bar_ptr),_1+_2);
function<void(int x)> f1=weak_fn(&foo::bar,bar_ptr);
function<void()> f1=bind(weak_fn(&foo::bar,bar_ptr),0);

The code availible from:

http://art-blog.no-ip.info/files/weak_fn.tar.gz

It is very initial implementation that gives functions from 0 to 3
parameters.

- I just want to be sure if this is correct direction?
- Comments on implementaions? Can it be done better?
- Do I miss something?

Thanks,
   Artyom

      


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk