Friday, September 4, 2009

C++ local_scope<> template

If you write a lot of code (and I know, some of the readers
actually do :), depending on your style, you often run
into situations where you allocate some ressource like
fopen()ing some files or allocing memory and later
you realize some error-condition and you properly need
to fclose()/free() all the stuff in the right order
and depending on what was allocated yet.
This leads to a lot of copy-n-paste code and often
plain wrong code or even better security breaches :)

If you like C++, you can have a look here to avoid
all these problems.

You can register FILE pointers, file-descriptors or
memory regions to a local_scope<> template and it
automatically closes/releases ressources when you leave scope
(also in right order).It is as easy as

local_scope<int> fd(open("/tmp/x2", O_RDONLY), close);

and you can use fd afterwards like you'd normally use
your descriptor. If you need to return due to some
other error condition, the file is closed when the
scope is left.Other ressources like lock's etc could easily
be added by extending local_scope<>.


taviso said...

And for those of us who think C++ is evil, you can do something like

#define scoped __attribute__((cleanup(cleanup)))

scoped void *foo;

To call cleanup(&foo) when foo goes out of scope, obviously without evil templates you must define different qualifiers for different types :-)

Sebastian said...

nice, reminds me of -finstrument-functions :)

Andre said...

Nice idea for a "generic auto_ptr". I will try this in my next C++ project :)

BTW: Same applies to sockets.