noreturn

Microsoft 专用

__declspec 属性告知编译器函数不会返回。 然后,编译器就会知晓调用 __declspec(noreturn) 函数后的代码是不可访问的。

如果编译器找到带有不返回值的控制路径的函数,则它会生成警告 (C4715) 或错误消息 (C2202)。 如果控制路径由于永不返回的函数而无法访问,则请使用 __declspec(noreturn) 阻止警告或错误。

注意

__declspec(noreturn) 添加到到预期返回的函数可能会导致未定义的行为。

示例

在以下示例中,当 isZeroOrPositive 的参数为负数时,将调用 fatal。 该控制路径中没有 return 语句,这会生成警告 C4715,指示并非所有控制路径都返回值。 将 fatal 声明为 __declspec(noreturn) 可以缓解该警告,这是可取的,因为它没有任何意义(因为 fatal() 会终止程序)。

// noreturn2.cpp
#include <exception>

__declspec(noreturn) void fatal()
{
   std::terminate();
}

int isZeroOrPositive(int val)
{
   if (val == 0)
   {
      return 0;
   }
   else if (val > 0)
   {
      return 1;
   }
   // this function terminates if val is negative
   fatal();
}

int main()
{
   isZeroOrPositive(123);
}

结束 Microsoft 专用

另请参阅

__declspec
关键字