std::function vs raw function pointer

Hi all, I wanted to hear your thoughts regarding std::function

std::function<void()> callback;

and raw function pointers

void (*fooPtr)(void)

when do you favor one over the other?

Thanks
The raw function pointer allows only to pass pointers to free functions. You cannot pass C++ constructs like lambda or member functions. With std::bind(...) you can pass additional paramters. See:

http://www.cplusplus.com/reference/functional/function/?kw=function
http://www.cplusplus.com/reference/functional/bind/?kw=bind

Note that when passing a member function you need to make sure that the associated object exists when calling that function.

when do you favor one over the other?
Use raw function pointer when you want that just a pointer to a free function is passed. If you want more flexibility use std::function.
std::function<> also has much greater overhead - which may or may not be a consideration.
The raw function pointer allows only to pass pointers to free functions. You cannot pass C++ constructs like lambda or member functions
It seems you can.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

typedef void (*func)(int i);

void f(func fu)
{
  fu(1);    
}

int main()
{
  f([] (int i) {std::cout << i << '\n';});

}

http://cpp.sh/4o5yl
You can pass lambdas only if no capture clause is specified, in which case the compiler converts to a regular function pointer.
@seeplus,
good to know that. Thanks for pointing it out.
@Thomas,
I would've favored a raw function pointer but I couldn't send a lambda to register my callback function because the function is a member of a class.

1
2
3
4
5
6
7
8
9
class ClassA
{
    public:
        ClassA
        {
            ClassB::Bind([this](){this->Func(); }); // Doesn't work if Bind is expecting a raw function pointer but works with std::function
        }
        void Func() { /* Do something */ } 
}


I think it's because when a function is a member of a class, the function receives an invisible parameter, in my example Func is actually Func(ClassA) while the function pointer is expecting a function with no params.
Thanks everyone for contributing to this thread and sharing your insights!
The lambda has a capture clause...........
Topic archived. No new replies allowed.