title: golang-style "defer" in C++
body: <p>I was reading about the go language's <a href="http://blog.golang.org/defer-panic-and-recover" rel="noreferrer">defer</a> statement. It allows you to specify an action to take when a function has ended. For example, if you have a file pointer or resource, instead of writing free/delete with every possible return path, you just need to specify the defer function once.</p>
  
  <p>It looks like an analogue might be coming to C++ eventually (<a href="https://stackoverflow.com/questions/32432450/what-is-standard-defer-finalizer-implementation-in-c">What is standard defer/finalizer implementation in C++?</a>, <a href="https://stackoverflow.com/questions/30405269/will-there-be-standardization-of-scope-guard-scope-exit-idioms">Will there be standardization of scope guard/scope exit idioms?</a>) Until then, is there anything unforeseen about doing it with an object whose destructor makes a callback? It looks like the <a href="https://isocpp.org/wiki/faq/dtors#order-dtors-for-locals" rel="noreferrer">destructor order for local variables is sane</a> and that it also handles exceptions well, though maybe not exiting on signals.</p>
  
  <p>Here is a sample implementation... is there anything troubling about it?</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;functional&gt;
  using namespace std;
  
  class FrameExitTask {
      std::function&lt;void()&gt; func_;
  public:
      FrameExitTask(std::function&lt;void()&gt; func) :
      func_(func) {
      }
      ~FrameExitTask() {
          func_();
      }
      FrameExitTask&amp; operator=(const FrameExitTask&amp;) = delete;
      FrameExitTask(const FrameExitTask&amp;) = delete;
  };
  
  int main() {
      FrameExitTask outer_task([](){cout &lt;&lt; "world!";});
      FrameExitTask inner_task([](){cout &lt;&lt; "Hello, ";});
      if (1+1 == 2)
          return -1;
      FrameExitTask skipped_task([](){cout &lt;&lt; "Blam";});
  }
  </code></pre>
  
  <p>Output: <code>Hello, world!</code></p>