I've read the article about scope guards ([Generic: Change the Way You Write Exception-Safe Code — Forever](http://www.ddj.com/cpp/184403758)) in DDJ and I understand their common use.

However, the common use is to instantiate a particular stack guard on the stack for a particular operation, e.g.:

```
{
    FILE* topSecret = fopen("cia.txt");
    ON_BLOCK_EXIT(std::fclose, topSecret);
    ... use topSecret ...
} // topSecret automagically closed

```

but what if I want to schedule cleanup operations in runtime, e.g. when I have a loop:

```
{
   vector<FILE*> topSecretFiles;
   for (int i=0; i<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
   }
}

```

Obviously, the above example wouldn't work, since `topSecret` would be closed along with the *for* scope. I'd like a scope guard pattern where I can just as easily queue up cleanup operations which I determine to be needed **at runtime**. Is there something like this available?

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?