class Widget { public: ... ~Widget() { ... } // assume this might emit an exception }; void doSomething() |
class DBConnection { public: ... static DBConnection create(); // function to return // DBConnection objects; params // omitted for simplicity void close(); // close connection; throw an |
class DBConn { // class to manage DBConnection public: // objects ... ~DBConn() // make sure database connections { // are always closed db.close(); } private: DBConnection db; }; |
{ // open a block DBConn dbc(DBConnection::create()); // create DBConnection object // and turn it over to a DBConn // object to manage ... // use the DBConnection object // via the DBConn interface } // at end of block, the DBConn // object is destroyed, thus // automatically calling close on // the DBConnection object |
既然能成功地调用 close 那就好了,但是如果这个调用导致了异常,DBConn 的析构函数将散播那个异常,也就是说,它将离开析构函数。这就产生了问题,因为析构函数抛出了一个烫手的山芋。