Boost logo

Boost :

Subject: Re: [boost] [Function] Problem using target() with boost::mem_fn and boost::bind
From: Daniel Walker (daniel.j.walker_at_[hidden])
Date: 2008-12-03 15:54:33


On Wed, Dec 3, 2008 at 3:14 PM, Pengcheng Song
<pengcheng.simon_at_[hidden]> wrote:
<snip>
> A a1;
> boost::function<double(double)> f1 = boost::bind( boost::mem_fn(&A::Area),
> &a1, _1, 2.5 );
> double s1 = f1(2.0); // this works
> FunctionType f2 = *f1.target<FunctionType>() ; // Error: this would crash
<snip>
> Is this an expected behavior? Your feedback would be greatly appreciated.

Yes, because the type of the wrapped function object is not
FunctionType, it's the return type of bind(). (Unfortunately, the
return type of bind() is not formally specified.) When boost::function
cannot perform the runtime conversion, it returns a null pointer as
documented. The crash is actually caused when you dereference this
pointer. If you make the following changes, you're code should be
safe.

    FunctionType* f2 = f1.target<FunctionType>() ; // no crash
    if(f2)
        s1 = Square( *f2, 2.0 );

Daniel Walker


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