其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·前两天看到的#pragma用法
·用C写的简单学生成绩管理系统
·射频芯片nRF401天线设计的分析
·入门系列--OpenGL最简单的入门
·简单的CreateRemoteThread例程-初学者必看
·BCB数据库图像保存技术
·GNU中的Makefile
·使用AutoMake轻松生成Makefile
·数据结构

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
Item 39. 异常安全之函数(Exception Safe Functions)

作者:未知 来源:月光软件站 加入时间:2005-5-13 月光软件站

Item 39. Exception Safe Functions

编写异常安全代码的难点不在于抛出和捕获异常,而是在于抛出和捕获之间要做的事情。当异常从抛出

到达捕获语句的过程中,这期间执行的函数在弹栈前需要清理它所使用的任何资源。通常,这就需要片

刻的思考以及一些常识。

以String的赋值操作为例:
 
String &String::operator =( const char *str ) {
    if( !str ) str = "";
    char *tmp = strcpy( new char[ strlen(str)+1 ], str );
    delete [] s_;
    s_ = tmp;
    return *this;
}

char *tmp 这个中间变量似乎有点多余,我们“可以”写成这样:
String &String::operator =( const char *str ) {
    delete [] s_;                                       
    if( !str ) str = "";
    s_ = strcpy( new char[ strlen(str)+1 ], str );
    return *this;
}

果真如此吗?
delete [] 根据约定可以保证不抛出异常,然而new[]可能抛出异常。在未知新的内存是否分配成功的

时候,我们却把s_的内存释放掉了。于是,String对象处于一个bad state。
Herb Sutter 告诉我们在这种情况下应该这样处理:首先在不改变重要状态的一边处理那些能够引发异

常的操作,而后用不能引发异常的操作结束整个过程(First do anything that could cause an

exception "off to the side" without changing important state, and then use operations that

can't throw an exception to finish up.)。

再看一例:

错误的写法:
void Button::setAction( const Action *newAction ) {             
    delete action_; // change state!                            
    action_ = newAction->clone(); // then maybe throw?          

繁琐的写法:
void Button::setAction( const Action *newAction ) {             
    delete action_;                                             
    try {                                                       
        action_ = newAction->clone();                           
    }                                                           
    catch( ... ) {                                              
        action_ = 0;                                            
        throw;                                                  
    }                                                           
}  

简单正确的写法:
void Button::setAction( const Action *newAction ) {
    Action *temp = newAction->clone(); // off to the side...
    delete action_; // then change state!
    action_ = temp;
}




相关文章

相关软件




月光软件程序下载编程文档电脑教程网站设计网址导航网络文学游戏天地幽默笑话生活休闲写作范文安妮宝贝
电脑技术编程开发网络专区谈天说地情感世界游戏元素分类游戏热门游戏体育运动手机专区业余爱好影视沙龙
音乐天地数码广场教育园地科学大观古今纵横谈股论金人文艺术医学保健动漫图酷二手专区地方风情各行各业

月光软件站·版权所有