I am trying to program a simple but flexible event system (basically, as an exercise, I know that there are existing libraries that have really good event handlers), and I came across a little stumbling block.
How can you check if a std::functiondelegate (possibly via lambda, perhaps though std :: bind) is a valid function / if the object for the member function still exists before it is called? I tried just using the std::function'sbool operator , but did not succeed.
Ideally, I would like A. to check somewhere other than the delegate function, and B. still has the code in action when the std :: function being checked is not a delegate.
Any ideas?
Edit: Here is the source for the test in which I ran
#include <iostream>
#include <string>
#include <functional>
class Obj {
public:
std::string foo;
Obj(std::string foo) : foo(foo) {}
std::function<void()> getDelegate() {
auto callback = [this]() {this->delegatedFn();};
return callback;
}
void delegatedFn() {
std::cout << foo << std::endl;
}
};
int main() {
Obj* obj = new Obj("bar");
std::function<void()> callback = obj->getDelegate();
callback();
delete obj;
if(callback) {
std::cout << "Callback is valid" << std::endl;
callback();
}
else {
std::cout << "Callback is invalid" << std::endl;
}
return 0;
}
source
share