title: Simple way to execute code at the end of function scope
body: <p>In test code occasionally I want to set/mock some global variables and at the end of test/scope I want to restore these variables. For example:</p>
  
  <pre><code>BOOST_AUTO_TEST_CASE(HttpClientCsrf)
  {
      std::string csrfSave = Http::getCsrfToken();
      ... some test code
      Http::setCsrfToken(csrfSave); // restore csrf
  }
  </code></pre>
  
  <p>Obvious problem here is that if <code>some test code</code> returns (or throws) before reaching the end you won't restore that <code>csrfSave</code> variable. So, simple improvement is to write some simple struct wrapper that restores the value automatically in dtor:</p>
  
  <pre><code>struct CsrfSave
  {
      std::string csrfSave;
      CsrfSave()
      {
          csrfSave = Http::getCsrfToken();
      }
      ~CsrfSave()
      {
          Http::setCsrfToken(csrfSave);
      }
  };
  BOOST_AUTO_TEST_CASE(HttpClientCsrf)
  {
      CsrfSave csrfSave;
      ... some test code
      // dtor of CsrfSave restores csrf
  }
  </code></pre>
  
  <p>This solves the problem in general, however, for each function you'd need to write lots of boilerplate code. So, the question is: what are shortest and simplest approaches could be used to achieve the same, while minimizing and possibly avoiding all that boilerplate.</p>
  
  <p>One such approach that I use, and I'm not too happy about it:</p>
  
  <pre><code>BOOST_AUTO_TEST_CASE(HttpClientCsrf)
  {
      std::string csrfSave = RBX::Http::getLastCsrfToken();
      shared_ptr&lt;void&gt; csrfSaveScope(NULL, [&amp;](void*) {
          RBX::Http::setLastCsrfToken(csrfSave);
      });
      ... some test code
  }
  </code></pre>
  
  <p>Is there anything better? I'd prefer to avoid writing any utility classes and would prefer to avoid boost (unless it's something that's included in next std).
  This kind of pattern happens quite often in different projects (that do not share code) and each time I end up writing either simple struct wrapper or generic wrapper that takes lambda and I would like to see other approaches that can be coded in-place just like I showed in my shared_ptr exmpale</p>