What is the point of noreturn?(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()
.
这篇关于noreturn 的意义何在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:noreturn 的意义何在?


基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01