c++ std::bind keeping object alive
c++, c++11
Solution
You are binding to a copy of `foo`; that copy lasts as long as the bound function object, while the original `foo` is destroyed at the end of its scope.
If you don't want to keep it alive, then bind to a pointer (`&foo`) or a reference (`std::ref(foo)`); and then you must be careful not to call the function object once `foo` has gone out of scope. Note that there's no way to tell from the function object that this has happened; calling it will give undefined behaviour.
In order to safely disconnect the object when it's destroyed, you would have to either arrange for its destructor to reassign `onclick`, or make some other object responsible for first reassigning `onclick`, and then destroying the object.
Problem
Here is the code, it's pretty straightforward. ``` class Foo { public: void print() { std::cout<<"Foo::print\n"; } }; Game::Game() { { Foo foo; player.onclick = bind(&Foo::print,foo); } player.onclick(); } ``` After the inner scope is done the foo object goes out of scope, but the print method is still called, I guess this happens because player holds a reference to the foo object? Is there a way to stop this from happening? I don't want objects to stay alive and receive events when they are supposed to be destroyed. Thanks.