views:

340

answers:

6

I'm a C++ amateur. I'm writing some Win32 API code and there are handles and weirdly compositely allocated objects aplenty. So I was wondering - is there some wrapper class that would make resource management easier?

For example, when I want to load some data I open a file with CreateFile() and get a HANDLE. When I'm done with it, I should call CloseHandle() on it. But for any reasonably complex loading function there will be dozens of possible exit points, not to mention exceptions.

So it would be great if I could wrap the handle in some kind of wrapper class which would automatically call CloseHandle() once execution left the scope. Even better - it could do some reference counting so I can pass it around in and out of other functions, and it would release the resource only when the last reference left scope.

The concept is simple - but is there something like that in the standard library? I'm using Visual Studio 2008, by the way, and I don't want to attach a 3rd party framework like Boost or something.

A: 

MFC has some suitable primitives (look at CFile for example), but not the standard library.

sharptooth
Such a class does not sound very complex. Perhaps there is an example implementation on the web somewhere that I could copy-paste in my solution? What keywords should I use in Google for that?
Vilx-
Look at this for example: http://bbdsoft.com/win32.html First match for "CreateFile CloseHandle wrapper" query.
sharptooth
Also CFile and the like will simplify things greatly compared to writing all the code with raw Win32.
sharptooth
Nice, but I only used file handles as a common easy-to-understand example. In reality I'm dealing with SSPI and handles that need special closing functions and triple-dynamically-allocated-indirect structs. Rare stuff.
Vilx-
Then user jalf is right on the money. Right your own set of classes - it will take an hour.
sharptooth
+1  A: 

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.

Kerido
I only used file handles as a common easy-to-understand example. In practice things are...weirder.
Vilx-
Which handles did you mean then?
Kerido
SSPI handles like CredHandle, CtxtHandle and SecBufferDesc. The last one is a weird struct which contains a dynamically allocated array of structs where each struct has a pointer to a dynamically allocated buffer. In a nutshell, it's a variable sized collection of variable sized buffers. The releasing function isn't as trivial as just "delete". :(
Vilx-
Just found this: http://www.drdobbs.com/cpp/184401688. Unfortunately I didn't use SSPI so I don't know if the material is appropriate for your case.
Kerido
A: 

Visual C++ 2008 supports TR1 through the Feature Pack, and TR1 includes shared_ptr. I would use this -- it's a very powerful smart pointer class and can be generalized to do the type of resource management you are asking for.

TR1 is effectively an extension to the Standard. I believe it's still officially "pre-standard", but effectively you can consider it locked down.

mwigdahl
+4  A: 

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.

jalf
The best idea, IMHO. These classes are called handle guards...
SadSido
The code is bad since the struct can be copied. Look at http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
Kerido
@Kerido, maybe, maybe not. It depends on the semantics of the resource you're wrapping. I think it's fair to give jalf the benefit of the doubt and assume the posted code is just a simple illustrative example.
Kristo
@Kerido: So... add two lines making the copy constructor and assignment operator `private` and undefined?
Mike DeSimone
Yes, copying should definitely be prevented if you want a robust solution. I left it out to show a short and simple implementation (which will suffice if you don't try to get clever and copy it). An easy way to prevent copying is to inherit from `boost::noncopyable`, but yes, otherewise make copy ctor and assignment operator private.But as Kristo said, this was just intended to be illustrative. I intentionally left out the copy constructor for brevity.
jalf
A: 

Here's one based off the EnsureCleanup code from 'Windows via C/C++': http://www.codeproject.com/KB/cpp/template2003.aspx

RaptorFactor
A: 

I don't think there is anything in the standard library, and I also doubt that shared pointers (as in boost) can be used (since those would expect pointer to HANDLE, not HANDLE).

It shouldn't be hard to write one yourself, following the scope guard idiom (and making use of templates/function pointers etc if you so choose).

visitor