● 所谓“异常安全”,指的是当抛出异常时,要做到:
1> 资源无泄漏。申请的资源都释放掉。
2> 数据无破坏。数据都处于合法状态,不会出现无法解释的数据。
满足这两点,就做到了基本的“异常安全”。
如果能在异常发生时把程序返回到调用前的状态,那就做到了高级的“异常安全”。
如果能保证绝不抛出异常,那就是完美的“异常安全”。
● 如果某函数的异常列表是空的,表明它一旦出现异常,将是极严重的错误。比如:
int doSomething() throw();
此时,系统会自动调用unexpected_handler来处理异常。
● 一个用于多线程的菜单类:
class PrettyMenu { public: void changeBackground(std::istream& imgSrc); // change background ... // image private: Mutex mutex; // mutex for this object Image *bgImage; // current background image int imageChanges; // # of times image has been changed }; // 换背景时要执行互斥访问 void PrettyMenu::changeBackground(std::istream& imgSrc) { lock(&mutex); // acquire mutex (as in Item 14) delete bgImage; // get rid of old background ++imageChanges; // update image change count bgImage = new Image(imgSrc); // install new background unlock(&mutex); // release mutex }
上面的成员函数没做到那两点要求。如果new抛出bad_alloc异常,则:
1> 互斥锁就永远打不开了;
2> bgImage则指向了已经销毁的对象;
3> imageChanges非法地自增了。
所以,该函数不是异常安全的。
Item 13讲了如何用对象管理资源;Item 14讲了锁的释放。所以,函数可以改成:
void PrettyMenu::changeBackground(std::istream& imgSrc) { Lock ml(&mutex); // from Item 14: acquire mutex and // ensure its later release delete bgImage; ++imageChanges; bgImage = new Image(imgSrc); }
这样,就解决了锁的问题。
bgImage要靠“资源管理类”才行:
class PrettyMenu { std::tr1::shared_ptr<Image> bgImage; ... }; void PrettyMenu::changeBackground(std::istream& imgSrc) { Lock ml(&mutex); bgImage.reset(new Image(imgSrc)); ++imageChanges; }
1> 无需手动delete旧有的图像
2> 删除操作发生成新图像成功创建之后。因为reset要等new正常返回才能进入的。
这样,该函数达到了基本的“异常安全”。
为什么没有达到高级“异常安全”呢?因为在Image的构造中出现异常时,istream的状态还是无法恢复到以前。
copy and swap一般认为是达到高级“异常安全”的策略:
struct PMImpl { // PMImpl = "PrettyMenuImpl std::tr1::shared_ptr<Image> bgImage; int imageChanges; }; class PrettyMenu { ... private: Mutex mutex; std::tr1::shared_ptr<PMImpl> pImpl; }; void PrettyMenu::changeBackground(std::istream& imgSrc) { using std::swap; // see Item 25 Lock ml(&mutex); std::tr1::shared_ptr<PMImpl> pNew(new PMImpl(*pImpl)); pNew->bgImage.reset(new Image(imgSrc)); ++pNew->imageChanges; swap(pImpl, pNew); }
异常安全设计
1110

被折叠的 条评论
为什么被折叠?



