Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function pointer vs functors in C++

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.

like image 285
Gaurav Sehgal Avatar asked Jun 04 '16 21:06

Gaurav Sehgal


People also ask

Is functor a function pointer?

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.

What are functors in C?

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.

Why do we need functors?

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.

Are lambdas functors?

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.


2 Answers

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.

like image 127
DevSolar Avatar answered Oct 12 '22 23:10

DevSolar


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 };
like image 27
cwschmidt Avatar answered Oct 12 '22 22:10

cwschmidt