Re: throwing dtors...
"anon" <anon@no.invalid> wrote in message
news:gc1n78$kks$1@news01.versatel.de...
Chris M. Thomasson wrote:
Is it every appropriate to throw in a dtor? I am thinking about a simple
example of a wrapper around a POSIX file...
Take a look here:
http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.13
[...]
Well, AFAICT, it seems like C++ destructors are really not all that good for
gracefully handling critical shutdown operations in dtors, such as
`fclose()'. Where am I going wrong? It seems like the only way to avoid
throwing from a dtor would be doing something along the lines of:
// example on how to handle EINTR or perhaps even EAGAIN
______________________________________________________________________
class file {
FILE* m_handle;
// returns true to retry; or false to continue...
bool (*m_fp_on_fclose_dtor) (int);
public:
file(bool (*fp_on_fclose_dtor) (int) = NULL, ...)
: m_fp_on_fclose_dtor(fp_on_fclose_dtor) {
// [...];
}
~file() throw() {
while (fclose(m_handle) == EOF) {
if (m_fp_on_fclose_dtor && !
m_fp_on_fclose_dtor(errno)) {
break;
}
}
}
};
static bool on_fclose_dtor(int status) {
switch (status) {
case EINTR:
return true;
case EAGAIN:
sleep(1);
return true;
default:
std::terminate();
}
}
int main() {
{
file f(on_fclose_dtor, ...);
// [...];
}
return 0;
}
______________________________________________________________________
Now, if a signal is thrown, or if the operation would block, the operation
will at least try to gracefully complete. All other errors KILL the program
dead... Sounds good to me.
However, this looks like a horrible hack. There has to be a MUCH between way
indeed!
:^o