Boost logo

Boost Users :

From: Jonathan Turkanis (technews_at_[hidden])
Date: 2005-01-21 16:22:40


Aaron W. LaFramboise wrote:
> 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.
>
>
> Given:
> 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.
>
> Problem:
> What is the best way to ensure that the file descriptor is
> automatically close()ed when the function is exited?

Since you don't want to write a special class for RAII, it sounds like a job for
scope_guard + lambda. scope_guard is currently an implementation detail in
multi_index, but will soon move to detail. The lambda expressions for control
stuctures

http://www.boost.org/doc/html/lambda/le_in_details.html#lambda.lambda_expressions_for_control_structures

and exceptions

http://www.boost.org/doc/html/lambda/le_in_details.html#lambda.exceptions

should allow you to do error handling. (I don't actually use lambda, but it
looks like it should work)

> So far, the best solution I have is to create a reusable helper (based
> on templates

This sound okay.

> and boost::function)

I don't see why you need 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!

This is the motivation for bind, lambda and scope guard.

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

Jonathan


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