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 的意义何在?


基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16