Effective C++ - 第八条 防止析构函数中有异常抛出
C++ 并不禁止在析构函数中抛出异常,担这应该被禁止,如果一个 std::vector 中有10个元素,当vector 析构的时候第一个元素的析构函数抛出了异常,会发生什么呢?
class Widget {
public:
...
~Widget() { ... } // 假设这里可能会抛出异常
};
void doSomething()
{
std::vector<Widget> v;
...
}当 v 销毁的时候,vector 中的所有元素都应该被销毁,如果其中第一个元素在析构的时候抛出异常,剩余的9个元素是否能被销毁是未定义的。所以这里可能会发生严重的资源泄露。
所以我们应当尽量避免在析构函数中抛出异常。
那如果我们一定要在销毁资源的时候调用一个会抛出异常的函数 改怎么办呢?
假设我们有一个DBConnection 的类,当对象销毁的时候我们应该关闭连接。
class DBConnection {
public:
...
static DBConnection create(); /
void close(); // 关闭连接,可能抛异常
};为了防止客户忘记调用 close 方法来关闭 DBConnection 对象,我们一般会创建一个资源管理类:
class DBConn {
public:
~DBConn() // 在资源管理类的析构函数里面关闭连接
{
db.close();
}
private:
DBConnection db;
};
{ // 使用时 定义一个 块级作用域
DBConn dbc(DBConnection::create());
} // 当 DBConn 离开作用域时, dbc 析构,接着关闭连接这里 DBConn 的析构函数会调用 close 函数,可能会触发异常。
我们可以在析构函数中catch 异常做一些处理:
// option 1 直接终止程序
DBConn::~DBConn()
{
try { db.close(); }
catch (...) {
// make log entry that the call to close failed;
std::abort();
}
}
// option2 忽略掉异常
DBConn::~DBConn()
{
try { db.close(); }
catch (...) {
// make log entry that the call to close failed;
}
}
这些2个方式都不好,因为它们没有提供机会给程序来处理这个错误。
更好的方式是修改 DBConn让客户有机会处理这个错误:
class DBConn {
public:
...
void close() // new function for
{ // client use
db.close();
closed = true;
}
~DBConn()
{
if (!closed) {
try { // close the connection
db.close(); // if the client didn’t
}
catch (...) { // if closing fails,
make log entry that call to close failed; // note that and ... // terminate or swallow
}
}
}
private:
DBConnection db;
bool closed;
};将 调用关闭的责任 从析构函数中挪出来,移交给DBConn的客户,仅当客户没有调用 close时,调用close 函数。这样的话,客户就有机会,也必须对这个可能的异常错误进行处理。
需要记住的事
*析构函数不应该抛异常,如果析构函数中调用的函数可能会抛异常,我们应该catch所有的异常。
*如果类的使用者需要处理析构函数中的某个抛异常的函数,我们应该提供一个这个函数的常规调用函数给使用者调用,以便其有机会处理这个异常错误。
