Boost logo

Boost Users :

From: Frank Birbacher (bloodymir.crap_at_[hidden])
Date: 2008-05-02 19:57:46


Hi!

Jose Martinez schrieb:
> I stumbled on the following behavior. I created a class function object and overloaded the () operator and would call
>
> t->async_wait(*this);

Function objects are passed by value. This call will copy your object.
The other posts already pointed that out.

My recommendation is to follow common practise: make the operator() "const":

void operator () (/*...*/) const
{...}

That way you cannot modify members. The "state" of the functor must be
stored outside of the functor object. This way the state doesn't get copied.

struct FunctorFoo
{
        FunctorFoo(int& counter)
        : counter(&counter)
        {}

        int* const counter;

        void operator() () const
        {
                ++*counter;
        }
};

(you could also use a "int& counter" member)

Frank


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