title: C++ RAII vs. defer?
body: <p>I've recently begun learning C++, previously I programmed in Go.</p>
  <p>I was recently informed that I should not be using <code>new</code> because exceptions thrown may cause the allocated memory not to be <code>free</code>d and result in a memory leak. One popular solution to this is RAII, and I found a really good explanation of why to use RAII and what it is <a href="https://www.tomdalling.com/blog/software-design/resource-acquisition-is-initialisation-raii-explained/" rel="nofollow noreferrer">here</a>.</p>
  <p>However, coming from Go this whole RAII thing seemed unnecessarily complicated. Go has something called <a href="https://gobyexample.com/defer" rel="nofollow noreferrer">defer</a> that solves this problem in a very intuitive way. You just wrap what you want to do when the scope ends in <code>defer()</code>, e.g. <code>defer(free(ptr))</code> or <code>defer(close_file(f))</code> and it'll automagically happen at the end of the scope.</p>
  <p>I did a search and found two sources that had attempted to implement the defer functionality in C++ <a href="https://www.gingerbill.org/article/2015/08/19/defer-in-cpp/#:%7E:text=The%20defer%20statement%20pushes%20a,better%20approach%20for%20C%2B%2B." rel="nofollow noreferrer">here</a> and <a href="http://the-witness.net/news/2012/11/scopeexit-in-c11/" rel="nofollow noreferrer">here</a>. Both ended up with almost exactly the same code, perhaps one of them copied the other. Here they are:</p>
  <p><strong>Defer implentation 1:</strong></p>
  <pre><code>template &lt;typename F&gt;
  struct privDefer {
      F f;
      privDefer(F f) : f(f) {}
      ~privDefer() { f(); }
  };
  
  template &lt;typename F&gt;
  privDefer&lt;F&gt; defer_func(F f) {
      return privDefer&lt;F&gt;(f);
  }
  
  #define DEFER_1(x, y) x##y
  #define DEFER_2(x, y) DEFER_1(x, y)
  #define DEFER_3(x)    DEFER_2(x, __COUNTER__)
  #define defer(code)   auto DEFER_3(_defer_) = defer_func([&amp;](){code;})
  </code></pre>
  <p><strong>Defer implementation 2:</strong></p>
  <pre><code>template &lt;typename F&gt;
  struct ScopeExit {
      ScopeExit(F f) : f(f) {}
      ~ScopeExit() { f(); }
      F f;
  };
  
  template &lt;typename F&gt;
  ScopeExit&lt;F&gt; MakeScopeExit(F f) {
      return ScopeExit&lt;F&gt;(f);
  };
  
  #define SCOPE_EXIT(code) \
      auto STRING_JOIN2(scope_exit_, __LINE__) = MakeScopeExit([=](){code;})
  </code></pre>
  <p>I have 2 questions:</p>
  <ol>
  <li><p>It seems to me that this <code>defer</code> is essentially doing the same thing as RAII, but much neater and more intuitively. What is the difference, and do you see any problems with using these <code>defer</code> implementations instead?</p>
  </li>
  <li><p>I don't really understand what the <code>#define</code> part does on these implementations above. What is the difference between the two and is one of them more preferable?</p>
  </li>
  </ol>