title: Dynamically created scope guards
body: <p>I've read the article about scope guards (<a href="http://www.ddj.com/cpp/184403758" rel="nofollow noreferrer">Generic: Change the Way You Write Exception-Safe Code — Forever</a>) in DDJ and I understand their common use.</p>
  
  <p>However, the common use is to instantiate a particular stack guard on the stack for a particular operation, e.g.:</p>
  
  <pre><code>{
      FILE* topSecret = fopen("cia.txt");
      ON_BLOCK_EXIT(std::fclose, topSecret);
      ... use topSecret ...
  } // topSecret automagically closed
  </code></pre>
  
  <p>but what if I want to schedule cleanup operations in runtime, e.g. when I have a loop:</p>
  
  <pre><code>{
     vector&lt;FILE*&gt; topSecretFiles;
     for (int i=0; i&lt;numberOfFiles; ++i)
     {
        char filename[256];
        sprintf(filename, "cia%d.txt", i);
        FILE* topSecret = fopen(filename);
        topSecretFiles.push_back(topSecret);
        ON_BLOCK_EXIT(std::fclose, topSecret); // no good
     }
  }
  </code></pre>
  
  <p>Obviously, the above example wouldn't work, since <code>topSecret</code> would be closed along with the <em>for</em> scope. I'd like a scope guard pattern where I can just as easily queue up cleanup operations which I determine to be needed <strong>at runtime</strong>. Is there something like this available?</p>
  
  <p>I can't push scope guard objects into a standard queue, cause the original object (the one I'm pushing) would be dismissed in the process. How about pushing heap-allocated stack guards and using a queue which deletes its members on dtor? Does anyone have a more clever approach?</p>