Re: throwing dtors...
Chris M. Thomasson wrote:
"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:
Destructors have to cleanup its objects, and they should (must) not fail.
// 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;
}
}
}
};
IMO This would be better:
class file {
FILE* m_handle;
public:
file()
{
// [...];
}
~file()
{
try
{
close_file();
}
// catch other exceptions
catch(...)
{
// log the error
}
}
void close_file()
{
// do whatever you can to close the file
// throw an exception in a case of an error
}
};
int main()
{
try
{
file obj;
// do stuff
obj.close_file();
}
catch(...)
{
// log error
// try to repair the damage
}
}
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.
With all other errors, your file will not be closed, and you have a
terminated program. Not very elegant solution ;)