noreturn 的意义何在?
[dcl.attr.noreturn] 提供以下示例:
[[ noreturn ]] void f() {
throw "error";
// OK
}
但是我不明白[[noreturn]]
的意义何在,因为函数的返回类型已经是void
了.
but I do not understand what is the point of [[noreturn]]
, because the return type of the function is already void
.
那么,noreturn
属性的意义何在?应该怎么用?
So, what is the point of the noreturn
attribute? How is it supposed to be used?
推荐答案
noreturn 属性应该用于不返回调用者的函数.这并不意味着 void 函数(确实返回给调用者 - 它们只是不返??回值),而是在函数完成后控制流不会返回到调用函数的函数(例如退出应用程序的函数,永远循环或抛出异常,如您的示例).
The noreturn attribute is supposed to be used for functions that don't return to the caller. That doesn't mean void functions (which do return to the caller - they just don't return a value), but functions where the control flow will not return to the calling function after the function finishes (e.g. functions that exit the application, loop forever or throw exceptions as in your example).
编译器可以使用它来进行一些优化并生成更好的警告.例如,如果 f
具有 noreturn 属性,编译器可能会在您编写 f() 时警告您
.同样,编译器会知道在调用 g()
是死代码;g();f()
后不会警告您缺少返回语句.
This can be used by compilers to make some optimizations and generate better warnings. For example if f
has the noreturn attribute, the compiler could warn you about g()
being dead code when you write f(); g();
. Similarly the compiler will know not to warn you about missing return statements after calls to f()
.
相关文章