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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…