Where do std::bind-created functors live?

你说的曾经没有我的故事 提交于 2019-12-30 18:08:19

问题


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

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?

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;
}

回答1:


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.

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.




回答2:


The std::bind function creates an instance of an unspecified class, and when that object goes out of scope and is destructed, so is the storage for that instance.

Just like instances of any other class with a destructor that releases some resource.



来源:https://stackoverflow.com/questions/25403522/where-do-stdbind-created-functors-live

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!