What wrapper class in C++ should I use for automated resource management?
Write your own. It's only a few lines of code. It's just such a simple task that it's not worth it to provide a generic reusable version.
struct FileWrapper {
FileWrapper(...) : h(CreateFile(...)) {}
~FileWrapper() { CloseHandle(h); }
private:
HANDLE h;
};
Think about what a generic version would have to do: It'd have to be parametrizable so you can specify any pair of functions, and any number of arguments to them. Just instantiating such an object would likely take as many lines of code as the above class definition.
Of course, C++0x might tip the balance somewhat with the addition of lambda expressions. Two lambda expressions could easily be passed to a generic wrapper class, so once C++0x supports comes around, we might see such a generic RAII class added to Boost or something.
But at the moment, it's easier to just roll your own whenever you need it.
As for adding reference counting, I'd advise against it. Reference counting is expensive (suddenly your handle has to be dynamically allocated, and reference counters have to be maintained on every assignment), and very hard to get right. It's an area just bursting with subtle race conditions in a threaded environment.
If you do need reference counting, just do something like boost::shared_ptr<FileWrapper>
: wrap your custom ad-hoc RAII classes in a shared_ptr
.
Essentially, fstream
is a good C++ wrapper for file handles. It's part of the standard which means it is portable, well tested, and extensible in an object-oriented manner. For file resources, it is a great concept.
However, fstream
only works for files, not for generic handles, i.e. threads, processes, synchronization objects, memory-mapped files, etc.