|
Boost : |
Subject: Re: [boost] Weak functor: Interested? (How to boost::bind to a weak_ptr)
From: yuri kilochek (yuri.kilochek_at_[hidden])
Date: 2012-01-10 12:19:56
>2012/1/10 VladimÃr TÅebický <vladimir.trebicky_at_[hidden]>
>
> Hi!
>
> I saw people asking how to do boost::bind using a weak pointer.
> Generally it's not possible without first specifying what should
> happen if the weak_ptr cannot be converted to shared_ptr. The
> "weak_fn" I wrote is a small class holding a member pointer, a weak
> pointer and a "policy":
>
> * It is callable so you can insert it to boost::bind.
> * You can construct it using free function templates.
> * The policy says what should happen when the object is called yet the
> weak_ptr cannot be converted to shared_ptr.
> * It's implemented both using variadic templates and Boost.Preprocessor.
>
> Copy of the help comment:
>
> /** Returns a callback that can be used eg. in boost::bind. When called, it
> Â * tries to lock weak_ptr to get a shared_ptr. If successful, it calls
> Â * given member function with given arguments. If not successful, it calls given
> Â * policy functor. Built-in policies are:
> Â *
> Â * "ignore_if_invalid" - does nothing
> Â * "throw_if_invalid" - throws "bad_weak_ptr"
> Â * "return_default_if_invalid" - returns given value
> Â *
> Â * Example:
> Â *
> Â * struct Foo {
> Â * Â Â void bar(int i) {
> Â * Â Â Â Â std::cout << i << std::endl;
> Â * Â Â }
> Â * };
> Â *
> Â * struct do_something {
> Â * Â Â void operator()() {
> Â * Â Â Â Â std::cout << "outdated reference" << std::endl;
> Â * Â Â }
> Â * };
> Â *
> Â * int main()
> Â * {
> Â * Â Â boost::shared_ptr<Foo> sp(new Foo());
> Â * Â Â boost::weak_ptr<Foo> wp(sp);
> Â *
> Â * Â Â boost::bind(boost::weak_fn(&Foo::bar, wp), _1)(1);
> Â * Â Â sp.reset();
> Â * Â Â boost::bind(boost::weak_fn(&Foo::bar, wp), 1)();
> Â * Â Â boost::bind(boost::weak_fn(&Foo::bar, wp, do_something()), 1)();
> Â * }
> Â */
>
> What's missing:
>
> * Cannot point to a free function. Only member functions.
> * ?
>
> Wdys?
>
> Vladimir.
I beleive people want to use std::weak_ptr with std::bind when they
want to store a callback, not just passing a functor to an algorithm,
and when people do that, that usually means storingin in an
std::function instance. We already have similar pattern for
shared/weak pointers, so wouldn't it be better to adopt an existing
desing and make weak_fn noncallable, but with the ability to obtain an
std::function instance from it, that would store a strong reference to
the object via shared_ptr?
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk