函数指针可以指向自由函数、函数对象、成员函数调用的包装器等任何内容。
但是, 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;
}
std::bind
按值返回一个对象(对象的确切类型是标准库的实现细节)。该对象存储所有必要的状态,其析构函数执行所有必要的清理。
请注意,您的向量不存储指针 - 它存储std::function
对象。 Astd::function
object 内部存储创建它的对象(函数指针或由std::bind
在你的情况下),并且它的析构函数正确地销毁了存储的对象。销毁函数指针不会执行任何操作。销毁类类型的对象会调用其析构函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)