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


- STL 中有 dereference_iterator 吗? 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01
- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07