Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do std::bind-created functors live?

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;
}
like image 805
Sam Avatar asked Aug 20 '14 11:08

Sam


1 Answers

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.

like image 148
Angew is no longer proud of SO Avatar answered Sep 28 '22 08:09

Angew is no longer proud of SO