gpt4 book ai didi

c++ - c++17 中的动态异常规范是否无效?

转载 作者:太空宇宙 更新时间:2023-11-03 10:23:59 26 4
gpt4 key购买 nike

动态异常规范在 C++17 中是否无效?像这样

void f() throw(int);

最佳答案

一般 C++ guidelines discourages to use of exception specifications任何版本的 C++ 和新标准都删除了此功能。

E.30: Don't use exception specifications

Reason

Exception specifications make error handling brittle, impose arun-time cost, and have been removed from the C++ standard.

Example
int use(int arg)
throw(X, Y)
{
// ...
auto x = f(arg);
// ...
}

If f() throws an exception different from X and Y the unexpectedhandler is invoked, which by default terminates. That's OK, but saythat we have checked that this cannot happen and f is changed tothrow a new exception Z, we now have a crash on our hands unless wechange use() (and re-test everything). The snag is that f() may bein a library we do not control and the new exception is not anythingthat use() can do anything about or is in any way interested in. Wecan change use() to pass Z through, but now use()'s callersprobably needs to be modified. This quickly becomes unmanageable.Alternatively, we can add a try-catch to use() to map Z intoan acceptable exception. This too, quickly becomes unmanageable. Notethat changes to the set of exceptions often happens at the lowestlevel of a system (e.g., because of changes to a network library orsome middleware), so changes "bubble up" through long call chains. Ina large code base, this could mean that nobody could update to a newversion of a library until the last user was modified. If use() ispart of a library, it may not be possible to update it because achange could affect unknown clients.

The policy of letting exceptions propagate until they reach a functionthat potentially can handle it has proven itself over the years.

Note

No. This would not be any better had exception specifications beenstatically enforced. For example, see Stroustrup94.

Note

If no exception may be thrown, usenoexceptor its equivalent throw().

关于c++ - c++17 中的动态异常规范是否无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47727108/

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