Sam*_*Sam 7 c++ bind std functor
函数指针可以指向自由函数,函数对象,成员函数调用的包装器中的任何内容.
但是,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));
// bind creates a copy of 10.
// That copy does not go into the vector, because it's a vector of pointers.
// Where does it reside? Who deletes it after funcs is destroyed?
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Rei*_*ica 10
std::bind按值返回对象(对象的确切类型是标准库的实现细节).此对象存储所有必需的状态,其析构函数执行所有必需的清理.
请注意,您的向量不存储指针 - 它存储std::function对象.甲std::function对象内部存储从它被创建的对象(一个函数指针或通过返回的对象std::bind中的情况),和它的析构函数正确地破坏所存储的对象.销毁指向函数的指针什么都不做.销毁类类型的对象会调用其析构函数.