我发现,如果被调用函数不返回(即标记为_Noreturn
/[[noreturn]]
或者有一个__builtin_unreachable()
通话后)。这是有意为之的行为,而不是错过的优化,如果是的话,为什么?
示例1:
#ifndef __cplusplus
#define NORETURN _Noreturn
#else
#define NORETURN [[noreturn]]
#endif
void canret(void);
NORETURN void noret(void);
void foo(void) { canret(); }
void bar(void) { noret(); }
C: https://godbolt.org/z/pJfEe-
C++: https://godbolt.org/z/-4c78K
示例2:
#ifdef _MSC_VER
#define UNREACHABLE __assume(0)
#else
#define UNREACHABLE __builtin_unreachable()
#endif
void f(void);
void foo(void) { f(); }
void bar(void) { f(); UNREACHABLE; }
https://godbolt.org/z/PFhWKR
这是故意的,尽管可能存在争议,因为它会严重损害堆栈使用属性;出于这个原因,我什至欺骗编译器认为一个不能返回的函数可以。原因是许多 noreturn 函数是abort
-喜欢(或者甚至打电话abort
),并且运行调试器的人可能希望能够看到调用发生的位置——尾调用会丢失的信息。
引用:
- https://gcc.gnu.org/bugzilla/show_bug.cgi?id=10837
- https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56165
- https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67327
- etc.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)