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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With