本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
经验:异常安全函数即使发生异常也不会泄漏资源或同意不论什么数据结构败坏。这种函数区分为三种
可能的保证:class PrettyMenu{
public:
//...
void changeBackground(std::istream &imgSrc); //改变背景图像
//...
private:
Mutex mutex; //相互排斥器
Image *bgImage; //眼下的背景图像
int imageChanges;//背景图像被改变的次数
};
void PrettyMenu::changeBackground(std::istream &imgSrc){
lock(&mutex);
delte bgImage;
++imageChanges;
bgImage = new Image(imgSrc);
unlock(&mutex);
}
class PrettyMenu{
//...
std::tr1::shared_ptr<Image> bgImage; //以对象管理资源
//...
};
void PrettyMenu::changeBackground(std::istream &imgSrc){
Lock ml(&mutex); // 以对象管理资源
bgImage.reset(new Image(imgSrc)); // 以"new Image" 的运行结果设定 bgImage 内部指针
++imageChanges;
}
Effective C++ Item 29 为”异常安全”而努力是值得的
原文:http://www.cnblogs.com/hrhguanli/p/5060417.html