What is std::function and what overhead does it introduce compared to a lambda or function pointer?
Last updated
std::functionis a type-erased wrapper that can hold any callable (lambda, function pointer, functor) matching one signature, e.g.std::function<int(int)>.Overhead: an indirect call that usually blocks inlining, possible heap allocation for large captures (small ones use a small-buffer optimization), and a bigger object to copy.
Lambdas and templates keep the concrete type and inline for zero overhead. Function pointers are cheap but stateless. Use
std::functiononly when you must store differing callables behind one interface.