function pointer vs functors in C++

Gaurav Sehgal picture Gaurav Sehgal · Jun 4, 2016 · Viewed 10.8k times · Source

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.

Answer

DevSolar picture DevSolar · Jun 4, 2016

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.