why cannot use uncaught_exception in dtor?
Posted
by
camino
on Stack Overflow
See other posts from Stack Overflow
or by camino
Published on 2011-01-07T09:34:20Z
Indexed on
2011/01/07
9:54 UTC
Read the original article
Hit count: 176
c++
|exception-handling
Hi ,
Herb Sutter in his article http://www.gotw.ca/gotw/047.htm pointed out that we cannot use uncaught_exception in desturctor function,
// Why the wrong solution is wrong
//
U::~U() {
try {
T t;
// do work
} catch( ... ) {
// clean up
}
}
If a U object is destroyed due to stack unwinding during to exception propagation, T::~T will fail to use the "code that could throw" path even though it safely could.
but I write a test program, and T::~T in fact didn't use the "code that could throw"
#include <exception>
#include <iostream>
using namespace std;
class T {
public:
~T() {
if( !std::uncaught_exception() )
{
cout<<"can throw"<<endl;
throw 1;
} else
{
cout<<"cannot throw"<<endl;
}
}
};
struct U
{
~U() {
try
{
T t;
}
catch( ... )
{
}
}
};
void f()
{
U u;
throw 2;
}
int main()
{
try
{
f();
}
catch(...)
{}
}
output is : cannot throw
did I miss something?
Thanks
© Stack Overflow or respective owner