|
Re: Monolith: Facts, Failures, Fallacies, Falsehoods and Furphies
|
Posted: Dec 6, 2006 1:40 PM
|
|
> > I do not like these examples: > > > > > > ::stlsoft::scoped_handle<int> h1(::open("file.ext"), > > ::close); > > > > ::stlsoft::scoped_handle<FILE*> h2(file, ::fclose); > > > > > > because the resulting code will not check the return > value > > of close() resp. fclose() . > This > > can easily lead to unrecognized data loss. > > > > Closing files is a bit problematic with RAII. Imagine > an > > error occurs while the destructor is running. There is > no > > return value, we can throw no exception, and there is > no > > object left that we might check. > > This is a very good point, and one which is more involved > than either of us want to get into here. > > I'm going to note this down for the book, and make sure to > discuss the problems you've raised. > > For now, I'll just amend the examples in the doco to > pretend like the issue doesn't exist. ;-) (I'll mention > the issue in the docs as well, don't worry.) > > It's also worth noting that in many (most??) cases, > closing a file in this way, i.e. without checking, is a > reasonable tactic, and that something such as > scoped_handle is a very helpful tool in that regard. > Clearly, what's not reasonable is to not mention that it's > not always reasonable: sometimes RAII is not the > appropriate approach. > > Thanks > > Matthew
I have thought about this a little more, and I found the following: there are actually two different resources involved, the file handle and the file content. It is the the design of close() /fclose() that is problematic, because it mixes two different operations: buffer flushing and file handle deallocation. If we perform fsync()/fflush()/shutdown() so that the the only task that is left is releasing the file handle, the problem disappears, and scoped_handle can be used without regret.
So maybe we can extrapolate from this case and get the following rule of thumb:
Think twice about using RAII if the deallocation function perfoms more than one task at once.
Finally, if data consistency is really important, using a database may be simpler :-)
cheers, Rupert
|
|