C++ std::function vs Function Pointers: Flexibility vs Speed

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

AspectFunction pointerstd::function
Capturing lambdasNoYes
FunctorsNoYes
Size / allocationsPointer-sizedLarger; may heap for big captures
SpeedFaster indirect callSlower

Performance (typical)

Microbenchmarks often show:

  • direct call fastest
  • function pointer next
  • std::function slowest (still fine for UI/event paths)

Prefer templates (template <class F>) for hot generic algorithms to avoid type erasure.


Guidelines

SituationPrefer
C API / extern "C"function pointer
Capturing lambda storagestd::function or template
Hot inner looppointer or templated callback

Pitfalls

  • Dangling captures in lambdas stored in std::function
  • std::bad_function_call if empty

  • Performance optimization

Keywords

std::function vs function pointer, type erasure, callback performance