C++ std::function vs Function Pointers: Flexibility vs Speed
이 글의 핵심
Compare std::function and function pointers: performance tradeoffs, capture support, and API design tips.
For encapsulating requests as callable objects (undo queues, jobs), the Command pattern builds on the same callback ideas.
Introduction: “How should I store callbacks?”
Function pointers are small and fast but cannot carry capturing lambdas. std::function is flexible but has overhead.
This article covers:
- Capabilities
- Benchmark trends
- Design patterns
Comparison
| Aspect | Function pointer | std::function |
|---|---|---|
| Capturing lambdas | No | Yes |
| Functors | No | Yes |
| Size / allocations | Pointer-sized | Larger; may heap for big captures |
| Speed | Faster indirect call | Slower |
Performance (typical)
Microbenchmarks often show:
- direct call fastest
- function pointer next
std::functionslowest (still fine for UI/event paths)
Prefer templates (template <class F>) for hot generic algorithms to avoid type erasure.
Guidelines
| Situation | Prefer |
|---|---|
C API / extern "C" | function pointer |
| Capturing lambda storage | std::function or template |
| Hot inner loop | pointer or templated callback |
Pitfalls
- Dangling captures in lambdas stored in
std::function std::bad_function_callif empty
Related reading
- Performance optimization
Keywords
std::function vs function pointer, type erasure, callback performance
Related posts
- Browse the C++ series
- C++ Adapter Pattern