不归路的意义何在? [英] What is the point of noreturn?

查看:34
本文介绍了不归路的意义何在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[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() 后,编译器将知道不会警告您缺少 return 语句.

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().

这篇关于不归路的意义何在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆