title: C++11 scope exit guard, a good idea?
body: <p>I've written a small utility class for C++11 which I use as a scope guard for easier handling of exception safety and similar things.</p>
  
  <p>Seems somewhat like a hack. But I'm suprised I haven't seen it somewhere else using C++11 features. I think boost has something similar for C++98.</p>
  
  <p>But is it a good idea? Or are there potential problems I have missed? Is there already a similar solution (with C++11 features) in boost or similar?</p>
  
  <pre><code>    namespace detail 
      {
          template&lt;typename T&gt;
          class scope_exit : boost::noncopyable
          {
          public:         
              explicit scope_exit(T&amp;&amp; exitScope) : exitScope_(std::forward&lt;T&gt;(exitScope)){}
              ~scope_exit(){try{exitScope_();}catch(...){}}
          private:
              T exitScope_;
          };          
  
          template &lt;typename T&gt;
          scope_exit&lt;T&gt; create_scope_exit(T&amp;&amp; exitScope)
          {
              return scope_exit&lt;T&gt;(std::forward&lt;T&gt;(exitScope));
          }
      }
  
  
  #define _UTILITY_EXIT_SCOPE_LINENAME_CAT(name, line) name##line
  #define _UTILITY_EXIT_SCOPE_LINENAME(name, line) _UTILITY_EXIT_SCOPE_LINENAME_CAT(name, line)
  #define UTILITY_SCOPE_EXIT(f) const auto&amp; _UTILITY_EXIT_SCOPE_LINENAME(EXIT, __LINE__) = ::detail::create_scope_exit(f)
  </code></pre>
  
  <p>and it's used something like.</p>
  
  <pre><code>int main () 
  {
    ofstream myfile;
    myfile.open ("example.txt");
    UTILITY_SCOPE_EXIT([&amp;]{myfile.close();}); // Make sure to close file even in case of exception
    myfile &lt;&lt; "Writing this to a file.\n"; // Imagine this could throw
    return 0;
  }
  </code></pre>