Where do the std :: bind-created functions live?

A function pointer may point to something from a free function, a function object, a wrapper over a member function call.

However, the std :: bind functions created may have state as well as those created by the user. Where is this state allocated and who removes it?

Consider the following example: is the state (number 10) deleted when the vector is deleted? Who knows how to default on a functor and not point to a 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 a vector of pointers. // Where does it reside? Who deletes it after funcs is destroyed? return 0; } 
+7
c ++ functor std bind
source share
2 answers

std::bind returns the object by value (the exact type of the object is a detail of the standard library implementation). This object saves all the necessary state, and its destructor performs all the necessary cleaning.

Note that your vector does not save pointers - it stores std::function objects. The std::function object internally saves the object from which it was created (the function pointer or the object returned by std::bind in your case), and its destructor correctly destroys the saved object. Destroying a function pointer does nothing. Destroying an object of a class type calls its destructor.

+10
source share

The std::bind function creates an instance of an unspecified class, and when this object goes out of scope and collapses, there is storage for that instance.

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

+2
source share

All Articles