Re: throwing dtors...
On Oct 2, 5:25 am, "Chris M. Thomasson" <n...@spam.invalid> wrote:
Is it every appropriate to throw in a dtor?
Sure. There are special cases where the only reason to have a
destructor is for it to throw.
All such cases are, however, special cases, and objects of those
types should only exist in special contexts (typically, as
temporaries in a single expression).
I am thinking about a simple example of a wrapper around a
POSIX file...
That one definitly shouldn't throw.
________________________________________________________________________
class file {
FILE* m_handle;
public:
// [...];
~file() /* throw() */ {
int const status fclose(m_handle);
if (status) {
/* shi% hit the fan:
http://www.opengroup.org/onlinepubs/007908775/xsh/fclose.html
/*
// [what now?]
}
}
};
________________________________________________________________________
If you get to the destructor and the file hasn't been closed,
it's an error. It should only happen in two cases: your
unwinding the stack as a result of another error (which will
result in the generated file being deleted, or at least marked
as invalid), or there is an error elsewhere in the code (which
should result in an assertion failure).
How to properly handle `EAGAIN' in dtor? Well, what about any
error for that matter? I am a C programmer and only code C++
for fun, and some in-house projects. If I were really going to
create C++ application and release it into the wild, well, how
would you advise me to handle the case above?
Require an explicit close by the user, before the object is
destructed, and return a return code from that function.
FWIW: most of my file output is through a file wrapper class
whose destructor deletes the file if it is called before the
file is "committed"; it also has an option for linking several
such wrappers, so that all of the files will be deleted unless
all have been successfully "committed". (Also, my shutdown
routines flush cout, and generate an error if that fails.)
[...]
Please keep in mind that refusing to not handle an error from
`fclose' could resule is HORRIBLE things down the road...
Obviously. And since the error must be handled, you never count
on the destructor for the close. (In the normal case---it's
fine if you're cleaning up after another error, and are going to
delete the file anyway as a result of the other error.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34