I was reading some forum posts written long time ago and run into a problem like this:
How do you create an object such that you can pass a callback function to it, and when the object is destroyed the callback function is always executed?
I know that this callback function should be put in the destructor since RAII. And someone posted a solution code to this problem as following
class MyClass {
public:
MyClass(void (*cb)()) : done(cb) {}
~MyClass() {
if (done) {
try {
(*done)();
}
catch (...) {
// choice of exit, log, throw an alert to somewhere in the
//system, or ignore
}
}
}
private:
void (*done)();
};
But somehow I don't feel comfortable with this code.
- Since it is often advised not to
throw
in the destructor, but is it OK here at least in this code since the wholetry
,catch
block is inside the destructor? - Somehow I feel that it is not safe to dereference a pointer in a destructor, since the object pointed by the pointer may be in an invalid state during stack unwinding when there is another exception already thrown. But in this code, the function pointed to is a member function and in the destructor there is checking on this pointer, so is it perfectly OK in this case?
- Is there any better solution than this code?
Aucun commentaire:
Enregistrer un commentaire