在一个函数前面加[[noreturn]]是什么意思?

[[noreturn]] int func1()
{
    exit(0);
}

[[noreturn]] void func2()
{
    ;
}

网上看了一下,没怎么看懂。
我自己写代码试了一下,若一个有返回值的函数前面加[[noreturn]],内部不返回任何值,但是加个exit,可以运行,报警告。

func2就不会报错也不会警告。

这其中的机制到底是怎么样的?[[noreturn]]的目的是什么?应该用在什么情景下?

阅读 17.4k
1 个回答

这是C++11attribute specifier sequence( http://en.cppreference.com/w/... )

关于[[noreturn]],官方解释是

Indicates that the function does not return.
This attribute applies to function declarations only. The behavior is undefined if the function with this attribute actually returns.

specifier用来指示函数永不返回
有助于编译器进行编译优化(如尾递归等),
也可以用于抑制编译器给出不必要的警告(如int f(); f();,不加[[noreturn]]的话,编译器会警告f()的返回值被忽略)

但是,若函数的确有返回值,而你却指定[[noreturn]]的话,这就是未定义行为了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题