为啥一个绝对异常安全并且返回被删除元素的pop()是不可能的
the value being popped is returned to the caller only after the stack has been modified, but the process of copying the data to return to the caller might throw an exception. If this happens, the data just popped is lost; it has been removed from the stack, but the copy was unsuccessful! The designers of the std::stack interface helpfully split the operation in two: get the top element (top()) and then remove it from the stack (pop()), so that if you can’t safely copy the data, it stays on the stack. If the problem was lack of heap memory, maybe the application can free some memory and try again.——《CPlusPlusConcurrencyInAction\u0026gt;\u0026gt; 果然大牛的才是简洁精炼
■网友
异常通常出现在copy construction期间,最简单的情况 内存不够,临时变量拷贝不出来,但是值丢失了。所以取元素和弹出元素设计成两步,保证即使有异常情况,数据不会丢失。
EXCEPTION HANDLING: A FALSE SENSE OF SECURITY
The pop operation fails because the object at the top of the stack cannot be copied (not because the stack is empty). Clearly, the caller does not receive a T object. But what should happen to the state of the stack object on which a pop operation fails in this way? A simple policy would be that if an operation on a stack throws an exception, the state of the stack is unchanged. A caller that removes the exception\u0026#39;s cause can then repeat the pop operation, perhaps successfully.
Exceptional C++ by Herb Sutter
【为啥一个绝对异常安全并且返回被删除元素的pop()是不可能的】 Item 10:Writing Exception-Safe Code--Part 3
If that copy construction or copy assignment fails, then the Stack has completed its side effect (the top element has been popped off), but the popped value is now lost forever,because it never reached its destination(oops).
(Exceptional C++挺值得读一读的)
推荐阅读
- 同比■同比增长7.1%!2021年的第一个节你花了多少钱?
- “他是我第一个会说普通话的老师”:一对师生折射青海山村蝶变
- 有必要重新开个C店吗
- 为啥看到书柜上的藏书会有心旷神怡的感觉
- 大学再有三个月就结束了,没学到知识,参加一个软件测试培训机构好吗
- 为啥知乎上普便有一种【我在北上广深打工,所以拥有更好的视野】这样的错觉
- 为啥工商银行的用户体验如此之差
- 汽车|长安UNI-K又将开创一个新的"引力"纪元?
- 汽车|看了中消协4S店服务测评调查结果,终于知道法系车为啥卖不好了
- 你为啥从窝窝商城离职?
