std::function vs raw function pointer

Oct 7, 2020 at 9:38pm
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
Oct 8, 2020 at 7:27am
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.
Oct 8, 2020 at 8:45am
std::function<> also has much greater overhead - which may or may not be a consideration.
Oct 8, 2020 at 8:52am
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
Oct 8, 2020 at 9:04am
You can pass lambdas only if no capture clause is specified, in which case the compiler converts to a regular function pointer.
Oct 8, 2020 at 9:07am
@seeplus,
good to know that. Thanks for pointing it out.
Oct 8, 2020 at 10:35pm
@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.
Oct 8, 2020 at 10:39pm
Thanks everyone for contributing to this thread and sharing your insights!
Oct 9, 2020 at 9:07am
The lambda has a capture clause...........
Topic archived. No new replies allowed.