std::bind创建的函子在哪里?

Where do std::bind-created functors live?

本文关键字:在哪里 bind 创建 std      更新时间:2023-10-16

函数指针可以指向自由函数、函数对象、成员函数调用的包装器中的任何对象。

然而,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按值返回一个对象(对象的确切类型是标准库的实现细节)。该对象存储所有必需的状态,其析构函数执行所有必需的清理。

注意你的vector不存储指针——它存储std::function对象。std::function对象在内部存储创建它的对象(在您的例子中是std::bind返回的函数指针或对象),并且它的析构函数正确地销毁存储的对象。销毁指向函数的指针没有任何作用。销毁类类型的对象将调用其析构函数。

std::bind函数创建一个未指定类的实例,当该对象超出作用域并被销毁时,该实例的存储空间也将被销毁。

就像其他类的实例一样,通过析构函数释放资源