Boost Users :
From: Aaron W. LaFramboise (aaronrabiddog51_at_[hidden])
Date: 2005-01-21 15:39:58
I was writing some simple code today, and rediscovered this general sort
of problem, and realized I have not yet decided on an optimal solution.
1) During a particular function, a type-int variable is initialized with
a value corresponding to a POSIX file descriptor.
2) There are multiple paths of exit from the function, including both
returns and exceptions.
What is the best way to ensure that the file descriptor is automatically
close()ed when the function is exited?
An additional thorn is that there must be code for handling that case
where close() fails. The solution must handle both cases where I'd like
to throw an exception, or cases where I'd just like to print an error
message and continue.
I have considered various solutions, some involving throw away classes,
and none of them appear to be satisfactory.
So far, the best solution I have is to create a reusable helper (based
on templates and boost::function) that is created as an automatic
variable and is passed the file descriptor, and a functor (which may be
a boost.lambda expression) that calls close(), and contains any other
necessary error-processing code. But seriously, for such a simple
problem, this is insane!
Solutions I don't particularly like involve creating a non-reusable
throw-away class that handles just this one particular case, or lack
sufficient mechanisms for handling errors.
Aaron W. LaFramboise
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net