std :: bind创建的函子在哪里住? [英] Where do std::bind-created functors live?

查看:161
本文介绍了std :: bind创建的函子在哪里住?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个函数指针可以指向一个自由函数,一个函数对象,成员函数调用的包装器。

A function pointer can point to anything from a free function, a function object, a wrapper over a member function call.

但是,std :: bind函子可以有状态,以及定制创建的。在哪个状态被分配,谁在删除它?

However, the std::bind created functors can have state, as well as custom-created ones. Where that state is allocated, and who is deleting it?

考虑下面的例子 - 当向量被删除时状态(数字10)是否会被删除?谁知道在函子上调用一个删除器,并且函数指针上没有删除器。

Consider the below example - will the state ( the number 10) be deleted when the vector is deleted? Who know to call a deleter on the functor, and no deleter on the function pointer?

#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::bind returns an object by value (the object's exact type is an implementation detail of the standard library). This object stores all necessary state and its destructor does all the required cleanup.

请注意,你的向量不存储指针 - 它存储 std ::函数对象。 std :: function 对象在内部存储创建它的对象(函数指针或 std :: bind 在你的case),并且它的析构函数正确地销毁存储的对象。破坏函数的指针什么都不做。销毁类类型的对象会调用它的析构函数。

Notice that your vector does not store pointers - it stores std::function objects. A std::function object internally stores the object from which it was created (a function pointer or the object returned by std::bind in your case), and its destructor correctly destroys the stored object. Destroying a pointer to function does nothing. Destroying an object of class type invokes its destructor.

这篇关于std :: bind创建的函子在哪里住?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆