`void func() throw(type)` 有什么意义?
我知道这是一个有效的 C++ 程序。 函数声明中的 throw 有何意义? AFAIK 它什么都不做,也不用于任何用途。
#include <exception>
void func() throw(std::exception) { }
int main() { return 0; }
I know this is a valid c++ program.
What is the point of the throw in the function declarement? AFAIK it does nothing and isnt used for anything.
#include <exception>
void func() throw(std::exception) { }
int main() { return 0; }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(6)
谈场末日恋爱2024-08-15 10:12:12
这是 C++ 异常规范。它声明特定函数可能会抛出 std::exception
类型。
一般来说,C++ 中的异常规范被认为是需要避免的功能。这是一个奇怪的特性,因为它的行为是在编译时声明的,但仅在运行时检查(与 Java 的版本非常不同)。
这是一篇很好的文章,详细介绍了该功能
口干舌燥2024-08-15 10:12:12
基本上是这样的:
void func() throw(std::exception,B) { /* Do Stuff */}
只是这样的简写:
void func()
{
try
{
/* Do Stuff */
}
catch(std::exception const& e)
{
throw;
}
catch(B const& e)
{
throw;
}
catch(...)
{
unexpected(); // This calls terminate
// i.e. It never returns.
}
}
调用终止()很少是您想要的,因为堆栈没有展开,因此您在 RAII 中的所有努力都被浪费了。该规则的唯一例外是声明一个空的抛出列表,这主要用于文档目的,以表明您支持不抛出异常保证(在这种情况下您仍然应该手动捕获所有异常)。
一些重要的(恕我直言)不应该抛出的地方是析构函数和 swap() 方法。析构函数很少被显式标记为“不抛出”,但 swap() 经常被标记为“不抛出”。
void myNoThrowFunc() throws() // No-Throw (Mainlly for doc purposes).
{
try
{
/* Do Stuff */
}
catch(...) // Make sure it does not throw.
{
/* Log and/or do cleanup */
}
}
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
它指定任何
std::exception
都可以从func()
抛出,而不能抛出任何其他异常。如果抛出其他内容,它将调用unexpected()
函数,该函数默认调用terminate()
。这意味着抛出其他内容几乎肯定会终止程序,就像未捕获的异常一样,但实现必须强制执行此操作。这通常与在
func()
周围放置try{...}catch(){...}
块非常相似,这会抑制性能。通常,根据本周大师专栏,异常规范是不值得的它。 Boost 指南 指出,空白 < 可能会有一点好处code>throws() 对于非内联函数,也有缺点。
It specifies that any
std::exception
can be thrown fromfunc()
, and nothing else. If something else is thrown, it will call anunexpected()
function which by default callsterminate()
.What this means is that throwing something else will almost certainly terminate the program, in the same manner as an uncaught exception, but the implementation will have to enforce this. This is normally much the same as putting a
try{...}catch(){...}
block aroundfunc()
, which can inhibit performance.Usually, exception specifications aren't worth it, according to the Guru of the Week column about it. The Boost guidelines say that there might be a slight benefit with a blank
throws()
for a non-inline function, and there are disadvantages.