简体   繁体   English

std::set 上的异常安全事务

[英]Exception safe transactions on std::set

std::set<T> e;

void f(/* Some parameters. */) {
    /* Some non-throwing code. */

    try {
        e.erase(a);
        e.insert(b);
        e.erase(c);
    } catch(...) {
        // Undo failed operations.
    }
}

I want f to have a strong exception guarantee, regardless of type T. Let's say, erasing a and inserting b succeedes, but erasing c throws.我希望 f 具有强大的异常保证,无论 T 类型如何。比方说,擦除 a 和插入 b 成功,但擦除 c 会抛出。 Then I have to undo the first two operations, but that would involve inserting and erasing from e in the catch block, but these operations can also throw.然后我必须撤消前两个操作,但这将涉及在 catch 块中从 e 插入和擦除,但这些操作也可以抛出。 Is there any way to perform this rollback?有没有办法执行这个回滚? I'm using C++17.我正在使用 C++17。

So if something throws on destruction, the strong exception guarantee is almost always pooched.因此,如果发生破坏,强异常保证几乎总是被抛弃。

When running stack unwinding due to exceptions, if a destructor throws your program calls std terminate for pretty much the same reason.由于异常而运行堆栈展开时,如果析构函数抛出您的程序调用 std terminate 几乎相同的原因。

When adding, you can just duplicate the entire collection, then add to the duplicate, then swap collections.添加时,您可以复制整个集合,然后添加到副本中,然后交换 collections。 Then you can destroy the duplicate;然后你可以销毁副本; but if that destruction throws, there really isn't a sane option.但如果这种破坏发生了,真的没有一个理智的选择。 You where stating this data is no longer needed, and are being informed that this operation failed.您不再需要说明此数据,并被告知此操作失败。 What does that even mean?那有什么意思? How do you undo "this data isn't needed"?您如何撤消“不需要此数据”?

Require lookup < (or == and hash ) to be exception-free.要求查找< (或==hash )无异常。 Do the same for destruction.对破坏做同样的事情。 Then .erase is also nothrow.然后.erase也是 nothrow。 Don't borrow trouble and posit insane types;不要借用麻烦和设置疯狂的类型; most insane types (they can exist) can be wrapped up in a sanity-wrapper and handle exceptions elsewhen.大多数疯狂的类型(它们可以存在)可以包装在一个 sanity-wrapper 中并在 elsewhen 时处理异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM