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<>.