函数指针可以指向自由函数,函数对象,成员函数调用的包装器中的任何内容.
但是,std :: bind创建的仿函数可以有状态,也可以是自定义创建的.分配该状态的位置,以及删除该状态的人员?
考虑下面的例子 - 删除向量时是否删除状态(数字10)?谁知道在函子上调用一个删除器,而函数指针上没有删除器?
#include <iostream>
#include <functional>
#include <vector>
using namespace std;
using namespace std::placeholders;
class Bar
{
public:
void bar(int x, int y) { cout << "bar" << endl; }
};
void foo(int baz){ cout << "foo" << endl; }
int main() {
typedef std::function<void(int)> Func;
std::vector<Func> funcs;
funcs.push_back(&foo); // foo does not have to be deleted
Bar b;
// the on-the-fly functor created by bind has to be deleted
funcs.push_back(std::bind(&Bar::bar, &b, 10, _1));
// …Run Code Online (Sandbox Code Playgroud)