我需要找到一种方法(请使用 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/