Boost logo

Boost :

From: Ross Smith (r-smith_at_[hidden])
Date: 2002-01-26 17:29:56

Thomas Maeder wrote:
> Am 2002.01.26 12:53 schrieb(en) Peter Dimov:
> > > But in general, the success of fclose() should be checked. Can
> > > shared_ptr be used then?
> >
> > Should it?
> Yes (in general). It's an operation that can fail. There are programs
> that have to behave differently if fclose() succeeds from when it fails.

The general solution to this sort of thing -- a resource whose "release"
operation may fail -- is to have a separate function that releases the
resource (in this case, flush the file). The normal code path will call
this before destruction. The destructor will close the file, but will
only do it without a preceing explicit flush if it's called as part of
stack unwinding after some other operation has thrown an exception.

> The std::fstream destructor closes the file if it is open. Failure is
> ignored, which seems to be a meaningful compromise since the close()
> member function can (and should) be called (and checked for failure)
> during normal program execution; i.e. the destructor only closes the
> file during stack unwinding because of an exception.

Which isn't quite what I described above. The appropriate "explicit
release" operation for a file is flush, not close. The normal code path
flushes the file, then the destructor closes it (among other things,
this avoids the overhead of checking in the destructor whether it's
already been closed).

I don't know if it's actually spelled out in so many words in the
relevant standards, but I've certainly always coded on the assumption
that, if you flush a file and don't write anything to it afterwards,
close is guaranteed not to fail.

(I also think -- in common, I gather, with a good many others -- that
iostreams are very badly designed in many ways and shouldn't be taken as
a model for future libraries.)

> This works fine if one object is the only owner of the file. I don't
> see how it can made to work with shared ownership.

I don't understand why multiple ownership would make a difference.

Ross Smith ...................................... Auckland, New Zealand
r-smith_at_[hidden] .........................
  "We need a new cosmology. New gods. New sacraments. Another drink."
                                                       -- Patti Smith

Boost list run by bdawes at, gregod at, cpdaniel at, john at