title: call callback function when object is destroyed
body: <p>I was reading some forum posts written long time ago and run into a problem like this: </p>
  
  <p>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?</p>
  
  <p>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</p>
  
  <pre><code>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)();
  };
  </code></pre>
  
  <p>But somehow I don't feel comfortable with this code.</p>
  
  <ol>
  <li>Since it is often advised not to <code>throw</code> in the destructor, but is it OK here at least in this code since the whole <code>try</code>, <code>catch</code> block is inside the destructor?</li>
  <li>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?</li>
  <li>Is there any better solution than this code?</li>
  </ol>