Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::function vs function pointer [duplicate]

  • Is there any differences?

  • Which is the best way to "save/transfer" function?

    function<void(int)> fcn = 
                        [](int par) {std::cout<<"fcn: "<<par<<std::endl; };
    void(*fcn_a)(int) = 
                        [](int par) {std::cout<<"fcn_a: "<<par<<std::endl; };
    
    
    fcn(12);
    fcn_a(12);
    
like image 504
Person.Junkie Avatar asked Dec 19 '22 07:12

Person.Junkie


2 Answers

std::function is more generic - you can store in it any callable object with correct signature (function pointer, method pointer, object with operator()) and you can construct std::function using std::bind.

Function pointer can only accept functions with correct signature but might be slightly faster and might generate slightly smaller code.

like image 169
tumdum Avatar answered Jan 07 '23 03:01

tumdum


In the case of a non-capturing lambda, using a function pointer would be faster than using std::function. This is because std::function is a far more general beast and uses type-erasure to store the function object passed to it. It achieves this through type-erasure, implying that you end up with a call to operator() being virtual.

OTOH, non-capturing lambdas are implicitly convertible to the corresponding function pointer. If you need a full-fledged closure however, you will have to assign the lambda to std::function, or rely on type deduction through templates, whenever possible.

like image 21
Pradhan Avatar answered Jan 07 '23 02:01

Pradhan