c++ - 在函数中使用 throw 关键字会产生 gcc 警告

标签 c++ gcc portability throw

我需要找到一种方法(请使用 C++03,不能使用 C++11)来消除 gcc 对以下(伪)代码产生的警告:

#include <stdexcept>

void throw_invalid()
{
  throw std::invalid_argument( "invalid" );
}

int foo(const char * str)
{
  if( str ) return 42;
  throw_invalid();
  // insert portable -fake- code that will get optimized away
}

我的代码需要至少在 gcc 5.x (-Wall) 和 Visual Studio 上没有警告。我的 throw_invalid 函数用于避免样板代码,并将异常集中在与无效参数相关的单个函数中。

目前警告是:

$ g++ -Wall -c foo.cxx 
b.cxx: In function ‘int foo(const char*)’:
b.cxx:13:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

我想避免添加伪造的 return -1(从未达到),因为它会使代码更难阅读。

最佳答案

在 C++11 中,您可以使用 attribute specifier [[noreturn]]

像这样:

[[noreturn]] void throw_invalid()
{
     throw std::invalid_argument( "invalid" );
}

int foo(const char * str)
{
    if( str ) return 42;
    throw_invalid();
    // insert portable -fake- code that will get optimized away
}

更新

就像 Walter 在他的评论中提到的那样,尽管函数 foo 是非 void 函数并且触发了错误,但函数 throw_invalid 需要该属性.将 throw_invalid 设置为 noreturn 将告诉编译器 foo 也不会在任何带有函数 throw_invalid 的代码路径时返回被带走了。

关于c++ - 在函数中使用 throw 关键字会产生 gcc 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34066441/

相关文章:

c - i = i + j; 和有什么区别?我+=j;用c语言?

c++ - GCC <= 4.9 的 std::atomic_store(shared_ptr) 替代方案?

c++ - 谁能告诉我如何编写一个简单的 C++ 代码来将我的数据(从变量)导出到 PDF 文件而不使用任何外部库或实用程序?

while-loop - 在多个 shell 中使用 while read 循环保留反斜杠

c++ - 如何从 gprof 中排除某个函数?

c++ - 给定不透明类型和数组,如何在 C++03 中交换两个 __m128i 变量?

c++ - 无法将项目添加到 Win32 列表框控件

c++ - glFrustum 没有创造透视

android - 无法使用 Ubuntu 在 eclipse 上制作和编译我的 NDK 项目

在 C 中创建没有依赖项的 Gotoxy() 函数