c++ - 如何在 C++ 中使用 [[noreturn]] 属性?

标签 c++ attributes

根据 stack overflow , [[noreturn]] 属性指定函数不返回。好的,没关系。

但是我不明白如何在程序中使用[[noreturn]] 属性。我尝试在我的代码中使用 [[noreturn]] 属性。但是当我在 GCC 编译器中编译我的代码时,出现了以下错误。

error: expected unqualified-id before ‘[’ token
 [[noreturn]] void f(int i) {
 ^
cp1.cpp: In function ‘int main()’:
cp1.cpp:11:6: error: ‘f’ was not declared in this scope
  f(10);

我的代码在这里:

#include <cstdlib>

[[noreturn]] void f(int i) {
  if (i > 0)
    throw "Received positive input";
  std::exit(0);
}

int main()
{
        f(10);
}

如何在C++中使用[[noreturn]]属性?

最佳答案

您肯定使用了不兼容的 C++11 编译器或 C++11 之前的编译器,或者您的标志未设置为 -std=c++11? (至少)。

如果您受困于 C++11 之前的编译器,您可以封装一个简单的宏,以希望可移植的方式使用内置编译器属性:

#ifdef __GNUC__
#define NO_RETURN __attribute__((noreturn))
#elif __MINGW32__
#define NO_RETURN __attribute__((noreturn))
#elif __clang__
#define NO_RETURN __attribute__((noreturn))
#elif _MSC_VER
#define NO_RETURN __declspec(noreturn)
#endif

然后用作:

NO_RETURN void f(int i) {
  if (i > 0)
    throw "Received positive input";
  std::exit(0);
}

关于c++ - 如何在 C++ 中使用 [[noreturn]] 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39543449/

相关文章:

c++ - 使用嵌套的 for 循环对 vector 中的元素求和

c++ - 我试图在从文件输入的字符串中查找年份

java - 如何将命名空间属性添加到 ksoap 信封?

attributes - 创建期间的 openssl 自定义属性

c++ - 在屏幕上旋转矩形

c++ - 我将如何删除此类对象? (C++)

attributes - Magento:addAttributeToFilter 但忽略没有此属性的产品?

复合文字和清理

c++ - 在 Linux 中更改 I2C 速度

asp.net - 从 DropdownList SelectedItem 获取属性