I’ve never used c++ functors before and so I’m just trying to understand how they work.
e.g. suppose we have this functor class
class MultiplyBy {
private:
int factor;
public:
MultiplyBy(int x) : factor(x) { }
int operator () (int other) const {
return factor * other;
}
};
Using it like this is clear to me:
MultiplyBy mult_3(3);
int x = mult_3(100);
Obviosuly the constructor of MultiplyBy is being called with the argument 3.
But in the following case, how is the constructor being called with the value in the array?
int array[5] = {1, 2, 3, 4, 5};
std::transform(array, array + 5, array, MultiplyBy(3));
You can think of transform being structured like this:
The functor is passed by value into the function.
So when you call like this:
Here you have created a temporary object. This is passed as a parameter value into transfer(). This results in the functor being copied into the function (not a problem since it has only a POD member and the compiler generated copy constructor works just fine). The parameter can then be used normally.
Note: The temporary object is destroyed at the end of the expression that it was created in (which will be after transform() returns).