【240916】C++ Lambda vs std::function vs Function Pointer

0 阅读1分钟

参考资料

  1. www.youtube.com/watch?v=aC-…

对比

C++ lambda IS NOT std::function.

// lambda: a C++ language construct for defining a n anonymous function.

// std::function: a type-erased wrapper around a "callable".

评论区老哥的总结

The way I understand it is:

  • if you're just passing a callable somewhere use a lambda (pass it as a generic callable type)
    • if you have to store the callable object or its implementation depends on runtime information then:
    • if the callable is stateless, use a function pointer
    • if the callable has state, then use a std::function

And since requiring your objects to be stateless is a big limitation, function pointers are almost never used except when you really need good performance is some hot code and you'd sacrifice flexibility to gain speed.