Boost logo

Boost :

From: Gregory Dai (gregory.dai_at_[hidden])
Date: 2007-04-08 20:36:36


On 4/1/07, Alexander Nasonov <alnsn_at_[hidden]> wrote:
>
> Hans Larsen wrote:
> > Hello,
> >
> > Better is such a big word. You still have to say in which way it is
> > better; readability, efficiency, simplicity, something else? ;-)
> Readability and simplicity. Compare
>
> std::FILE* f = NULL;
>
> try
> {
> f = std::fopen("/etc/passwd", "r");
> // ...
> }
> finally
> {
> if(f)
> std::fclose(f);
> }
>
> with
>
> std::FILE* f = std::fopen("/etc/passwd", "r");
> scope(exit)
> {
> if(f)
> std::fclose(f);
> }
>
> // ...
>
> Even without D's scope(exit) syntax it looks appealing
>
> std::FILE* f = std::fopen("/etc/passwd", "r");
> BOOST_SCOPE_EXIT(f, (f))
> {
> if(f)
> std::fclose(f);
> } BOOST_SCOPE_EXIT_END(f)

Well, I'm very late to this thread of discussion, but I'd like to add my
$0.02.

Why would we go through so much complexity? Remember the simple and basic
principle of RAII? In situations like this, you just make a simple wrapper
of the FILE*, with an implementation similar to that of a smart pointer such
as the auto_ptr, and let's name it auto_cfile, with a "FILE*&()" operator
member function to expose the FILE* it protects:

auto_cfile f(std::fopen("/etc/passwd","r"));
.... (uses of f as if it were a FILE*)

and the FILE* is automatically closed by auto_cfile's dtor when it goes out
of scope.

No need of a "try ... catch" block at all, much less of "finally," which is
an unnecessary addition in C#, IMHO.

<snip>

--
> Alexander Nasonov
> http://nasonov.blogspot.com
>
<snip>
-- 
Thanks,
Greg

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk