异常处理规范(Exception Handling Specification)

基本原则

程序设计的一个基本原则:

无论发生何种异常,应尽可能保证申请的资源(包括但不限于内存资源)被释放。

异常处理

在资源申请、释放在一个局部过程中时,可以采用的方式有:

try..catch

在申请一个资源那一刻开始,到资源释放的整个过程,使用try..catch将代码包含。以下是这个过程的标准写法:

MyClass* pObj = new MyClass; // 申请内存资源的开始
try
{
    ... // 对该内存资源的正常处理过程
}
catch(...)
{
    delete pObj;
    throw; // 将异常重新抛出
}
delete pObj;

重要提醒:

值得注意的问题是,这种做法下,资源释放代码一般情况都需要写多遍1。这显然不是一个好的习惯。

使用资源句柄类

将资源用类进行包装,由类进行资源的申请、释放操作。这种类我们称为资源句柄类(Resource Handle Class)2。在这种技术下,以上例子简化为很简单几句代码:

std::auto_ptr<MyClass> spObj(new MyClass);
... // 对该内存资源的正常处理过程

工作原理:

即使发生异常,C++编译器仍然可以保证,声明在栈中,并且已经被构造的自动变量在异常机制的“栈展开”过程中执行析构操作,从而保证了资源的释放。

这是我们推荐的方式。我们推荐对所有的资源3使用资源句柄类。这也是Bjarne Stroustrup(C++之父)推荐的方式。详细请参阅Programming with Exceptions

相关参考

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License

Subscription expired — please renew

Pro account upgrade has expired for this site and the site is now locked. If you are the master administrator for this site, please renew your subscription or delete your outstanding sites or stored files, so that your account fits in the free plan.