y destructors should never throw #le2LinYu

Hi Lin Yu,

You once asked me exactly why destructors should not throw. I just read about it. Compiler would turn a blind eye if your destructor calls some function1 (that in turn calls some function2, that in turn calls some function3 …) that could throw an exception. Over 5 years in production the destructor may not throw, but what happens when it does throw? Maybe nothing bad happens, but maybe one of these things happen

– if the destructor is invoked as part of stack unwinding, then system would probably terminate
– If your object’s destructor has the hidden (destructive) power to throw exceptions, then the STL containers won’t store this object. If you still put this object into an STL container, then I don’t know what happens. Perhaps undefined behavior. If your class is to be used with the STL, then the STL explicitly forbids exception throwing from your class destructor.
– your class can’t be used as member or base-class of another class

Even though the consequence is not documented, the language standard DOES specify when and where destructors should NOT throw. Looks like you might (in theory) get away with an exception thrown from a destructor, but many parts of c++ language do not allow it. In reality, the consequence is probably harmful rather than harmless.

I hope this letter clarifies the issue rather than add to your confusion. Feel free to reply.

Tan Bin

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s