class Widget { public: ... ~Widget() { ... } // assume this might emit an exception }; void doSomething() { std::vector ... } // v is automatically destroyed here |
class DBConnection { public: ... static DBConnection create(); // function to return // DBConnection objects; params // omitted for simplicity void close(); // close connection; throw an }; // exception if closing fails |
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 抛出异常,调用 abort。 DBConn::~DBConn() { try { db.close(); } catch (...) { make log entry that the call to close failed; std::abort(); } } |