Safe callback design
I have a callback class that is used in some places throughout my
application. It's constructed like this:
struct A {
void f();
}
A * callee = new A;
Callback_0 callback = CCallback_0(callee, &A::f);
callback can now be stored and invoked later. The problem with this is if
callee is destroyed between callback creation and callback invocation, the
program crashes (or worse).
The only solution I can think of so far: any class that wants to be a
callee must be inherited from a base Callee class:
class Callee {
public:
void registerCallback(const Callback& c) {
_callbacks.push_back(c);
}
~Callee() {
std::for_each(_callbacks.begin(), _callbacks.end(), [](Callback&
c){c.disable();});
}
private:
std::vector<Callback> _callbacks;
}
The downside of this design is that I have to inherit every class that
might be required to be called. Is there any better way? I'd prefer a
C++03 solution, I only have limited C++11 support (limited by MSVC2010 and
clang on Mac).
No comments:
Post a Comment