Boost logo

Boost Users :

From: François Duranleau (duranlef_at_[hidden])
Date: 2007-09-18 11:43:07


On Tue, 18 Sep 2007, Michael Bradley Jr wrote:

> Hi,
>
> I'm looking for a way to let the function object wrapper be stored by reference
> instead of by cloning/copying.
> It's said in [1] that someone can achieve this through the use of references,
> but i don't know how to apply it in this particular case.
>
>
> <code>
> class A {
> bool operator()(void) {return false;}
> };
>
> typedef boost::function<bool (void)> TEST;
>
> class B {
> void invoke(TEST obj);
> };
>
> When i pass an instance of A as a parameter to the invoke method of B then the
> whole object is copied. I just want it to be use
>
> </code>
>
> I've also use boost::ref without success
>
> class C {
> void invoke(TEST & obj);
> };
> doesn't work either!

boost::ref works. You can use it with your class B like this:

B b ;
A a ;

b.invoke( ::boost::ref( a ) ) ;

or

TEST obj = ::boost::ref( a ) ;
b.invoke( obj ) ;

It won't work for C because you will be initializing a non-const reference
from a temporary object. But for the latter use above, you might want to
do this:

class C {
void invoke(const TEST& obj);
};

and then

c.invoke( obj ) ;

it will save you a copy of the wrapper obj.

-- 
François Duranleau
LIGUM, Université de Montréal
"When there are others, I can perceive myself as an individual. If I am
  alone, then I will be the same as everything else. There will be no
  difference between myself and nothing!"
                                           - from _Neon Genesis Evangelion_

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net