What is the difference between using functors and function pointers. For example
//Functor
struct add_x
{
int x;
add_x(int y):x(y){}
int operator()(int y)
{
return x+y;
}
};
//Function
int (func)(int x)
{
return ++x;
}
std::vector<int> vec();
//fill vec with 1 2 3 4 5
int (*f)(int) = func;//Function pointer
std::transform(vec.begin(),vec.end(),f); //approach 1
std::transform(vec.begin(),vec.end(),add_x(1)); //approach 2
Both approaches work but i am sure there will be cases where one is preferred(or possible) over other.
Functors: Function Objects in C++ Both C and C++ support function pointers, which provide a way to pass around instructions on how to perform an operation.
A C++ functor (function object) is a class or struct object that can be called like a function. It overloads the function-call operator () and allows us to use an object like a function.
Functors give you more flexibility, at the cost of usually using slightly more memory, at the cost of being more difficult to use correctly, and at the cost of some efficiency.
Lambdas are basically just syntactic sugar that implement functors (NB: closures are not simple.) In C++0x, you can use the auto keyword to store lambdas locally, and std::function will enable you to store lambdas, or pass them around in a type-safe manner.
For one, the functor can contain internal state; a state that is valid for this invocation of the function object only. You could add static
variables to your function, but those would be used for any invocation of the function.
Second, the compiler can inline calls to the functor; it cannot do the same for a function pointer. This is why C++ std::sort()
beats the crap out of C qsort()
performance-wise.
functors can be even used to emulate lambda expressions (if you have to use an older compiler before C++11/C++14) to a certain extent, because they can have individual state (e.g. as member variables).
struct A {
int x; // state member can even be made private! Instance per functor possible
int operator()(int y) { return x+y }
};
or as lambda
auto lambda = [&x](int y) { return x+y };
function pointers can only get arguments, but are stateless, unless they access any global variables (which is really bad design and dangerous).
// global scope, anyone can accidentally manipulate and not thread-safe here, only one global instance possible!
inx x;
int (func)(int y) { return x+y };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With