简体   繁体   中英

Destructor throwing exception

I'm trying to understand why the destructors throwing exceptions is a very bad idea. By googling, I understand that if destructor throws, say, during destruction of the block-scope objects, the destruction of the obeject stopped and we get memory leak if there're the other objects destructors have not called for.

But by itself, the destructor throwing exceptions is so bad? For instance (the complete example):

struct A
{
    int a;
    char b;
    A() : a(10), b('a') { }
    ~A(){ throw std::exception(); }
};

int main()
{
    A a; //destructor throws, but there're no more objects to destruction 
         //therefore I think there's no memory leak
}

Do we get UB in the program above?

In this trivial example, the exception in bar() is thrown and the stack is unwound, destructing a, which throws another exception. Which exception could be thrown in this case?

struct A
{
    int a;
    char b;
    A() : a(10), b('a') { }
    ~A(){ throw std::exception(); }
};
void bar () 
{
    A a;
    throw std::exception();
}
int main()
{
    bar();
}

From C++ FAQ

During stack unwinding, all the local objects in all those stack frames are destructed. If one of those destructors throws an exception (say it throws a Bar object), the C++ runtime system is in a no-win situation: should it ignore the Bar and end up in the } catch (Foo e) { where it was originally headed? Should it ignore the Foo and look for a } catch (Bar e) { handler? There is no good answer — either choice loses information.

So the C++ language guarantees that it will call terminate() at this point, and terminate() kills the process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM