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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With