gpt4 book ai didi

c++ - d'tor 的函数尝试 block 是否应该允许处理抛出成员变量 d'tor?

转载 作者:行者123 更新时间:2023-12-03 06:54:18 25 4
gpt4 key购买 nike

我有一个类,它的析构函数是 noexcept(false) .我知道它只在某些情况下抛出,我想将它用作具有 noexcept 的类的成员变量析构函数。来自 https://en.cppreference.com/w/cpp/language/function-try-block我读到“从函数体中的任何语句抛出的每个异常,或(对于构造函数)从任何成员或基类构造函数,或(对于析构函数)从任何成员或基类析构函数抛出的异常,都将控制转移到处理程序序列,方式与异常相同抛出一个常规的 try block 会。”这让我认为这应该是正确的:

#include <exception>

class ConditionallyThrowingDtor {
public:
bool willThrow = true;
ConditionallyThrowingDtor() = default;
~ConditionallyThrowingDtor() noexcept(false) {
if (willThrow) {
throw std::exception();
}
}
};


class NonThrowingDtor {
public:
ConditionallyThrowingDtor x;
~NonThrowingDtor() noexcept try {
x.willThrow = false;
} catch (...) {
// Ignore because we know it will never happen.
}
};


int main() {
// ConditionallyThrowingDtor y; // Throws on destruction as expected.
NonThrowingDtor x;
}

https://godbolt.org/z/ez17fx (MSVC)

我对noexcept的理解和 ~NonThrowingDtor() 上的函数尝试 block 是那个noexcept保证它不会抛出(并且它通过本质上做 try { ... } catch (...) { std::terminate(); } https://en.cppreference.com/w/cpp/language/noexcept_spec 来做到这一点。但是带有 catch (...) 的函数尝试 block 并且没有额外的抛出应该保证它永远不会抛出。Clang 可以接受这个,但是正如 Godbolt 链接所示,MSVC 说

<source>(23): warning C4297: 'NonThrowingDtor::~NonThrowingDtor': function assumed not to throw an exception but does
<source>(23): note: destructor or deallocator has a (possibly implicit) non-throwing exception specification

最佳答案

~NonThrowingDtor() noexcept try {
x.willThrow = false;
} catch (...) {
// Ignore because we know it will never happen.
}

是“错误”的,等同于

~NonThrowingDtor() noexcept try {
x.willThrow = false;
} catch (...) {
throw;
}

很简单

~NonThrowingDtor() noexcept
{
x.willThrow = false;
}

为了不传播异常,你必须显式地使用return:

~NonThrowingDtor() noexcept try {
x.willThrow = false;
} catch (...) {
return; // Required to not propagate exception.
}

不幸的是,msvc 仍然以这种不会抛出的形式发出警告。
(另一方面,clang/gcc 不会警告隐式(但会警告显式)throw 在这种情况下)。

关于c++ - d'tor 的函数尝试 block 是否应该允许处理抛出成员变量 d'tor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64754867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com