In the wikipedia article about function objects it says such objects have performance advantages when used with for_each because the compiler can “inline” them.
I’m a bit foggy on exactly what this means in this context… or any context I’m embarrassed to say. Thanks for any help!
The last parameter of
for_eachtemplate is a functor. Functor is something that can be “called” using the()operator (possibly with arguments). By defintion, there are two distinctive kinds of functors:functors.
()operator (so called function objects) are also functors.Now, if you wanted to use an ordinary function as a functor for
for_each, it would look something like the followingIn this case the
for_eachtemplate is instantiated with [deduced] arguments<int *, void (*)(int &)>. Note that the actual functor value in this case is the function pointer&do_somethingpassed as the function argument. From the point of view offor_eachfunction this is a run-time value. And since it is a run-time value, the calls to the functor cannot be inlined. (Just like it is in general case impossible to inline any call made through a function pointer).But if we use a function object instead, the code might look as follows
In this case the
for_eachtemplate is instantiated with [deduced] arguments<int *, do_something>. The calls to the functor from insidefor_eachwill be directed todo_something::operator(). The target for the call is known and fixed at compile-time. Since the target function is known at compile-time, the call can easily be inlined.In the latter case we, of course, also have a run-time value passed as an argument to
for_each. It is a [possibly “dummy” temporary] instance ofdo_somethingclass we create when we callfor_each. But this run-time value has no effect on the target for the call (unless theoperator ()is virtual), so it doesn’t affect inlining.