为什么函数对象比函数指针更好?

Why are function objects better than function pointers?

来自 Wikipedia - Function object

A typical use of a function object is in writing callback functions. A callback in procedural languages, such as C, may be performed by using function pointers.[2] However it can be difficult or awkward to pass a state into or out of the callback function. This restriction also inhibits more dynamic behavior of the function. A function object solves those problems since the function is really a façade for a full object, carrying its own state.

  1. 为什么函数指针很难将状态传入或传出回调函数函数的动态行为?

  2. 如果函数不使用函数指针程序如何调用函数

  1. C中的函数指针而言,您需要将状态作为额外参数传递。这与 python、javascript 或 C++ 等具有闭包的语言相反。这意味着需要考虑额外结构的存储持续时间。

  2. C 程序员 使用函数指针。如果不使用函数指针,您将无法编写非常通用的代码。我们只是应用纪律并将捕获的状态作为函数参数传递到结构中。