[Cs3] Functors

Mikhail Nesterenko mikhail at cs.kent.edu
Mon Feb 28 10:55:29 EST 2022


> 
> So I was watching a lecture and I encounter this code:
> 
> class MyFunctor{
> public:
>    MyFunctor(int x) : x_(x) {}
>    void setx(int x){x_ = x;}
>    int operator() () {return x_;}    // overloading function operator
> private:
>    int x_;
> };
> 
> int main(){
>    // creating a functor object
>    MyFunctor addIt(5); // initializing to 5
>    vector<int> v(10);
> 
>    generate(v.begin(), v.end(), addIt);
> 
> In the lecture you said that there is a problem with this, but I was
> unable to understand because there was some audio issue. Can you
> please explain that to me?

What I probably said, and also what I said in class this semester, is:
the functor (the overloaded parenthesis operator) should not be
changing the state of the object (in this case addIt) when it is
invoked inside the algorithm (in this case generate()). The reason is
that there is no guarantee that the functor is invoked inside
generate() in sequence or in order of the elements in the range
specified by v.begin() and v.end(). To improve the efficiency of the
implementation, the implementers may process multiple elements out of
order or concurrently.

Thanks,
--
Mikhail


More information about the cs3 mailing list