Don't let exceptions escape destructors
Why don't you let the exception escape the destructor, and what are the problems that the exception will cause? It is clear that anomalies can lead to ambiguous behavior.
The following code:
Destructors are called when the container is destroyed, and if the destructor throws an exception, the remaining elements in the container should be destroyed or there may be a memory leak. At this point, if you continue to destroy other elements, there will be an exception, there are two exceptions. The presence of two exceptions can lead to ambiguous behavior. You will also encounter similar problems with other containers of the standard library or any container or array of TR1. What we need to do at this point is to terminate the program in general, to prevent the program from appearing ambiguous behavior
class Widget{public:……~Widget(){……}};void doSomething(){ std::vector<Widget> v; …… //v要析构,会调用Widget的析构函数}
In the destructor, sometimes it is unavoidable to throw an exception, as in the case of the book:
What should we do when a database shutdown fails?
classDBConnection{public:……void close();//关闭数据库};classDBConnection{public:…… ~DBConn()//析构函数关闭连接 { db.close(); }private: DBConnectiondb;};
There are two ways to avoid this problem:
1. If close throws an exception, terminate the program. This is usually done by calling abort.
2. It's a bad way to swallow this anomaly.
~DBConn()//析构函数关闭连接 { try{ db.close(); } catch(……) { //记录下对close调用的失败 std::abort();//退出 } }~DBConn()//析构函数关闭连接 { try{ db.close(); } catch(……) { //记录下对close调用的失败 } }
Effective C + + clause 8