C++ 在函数中使用throw关键字会生成带有gcc的警告
我需要找到一种方法(请使用C++03,不能使用C++11)删除gcc在以下(伪)代码上产生的警告:C++ 在函数中使用throw关键字会生成带有gcc的警告,c++,gcc,portability,throw,C++,Gcc,Portability,Throw,我需要找到一种方法(请使用C++03,不能使用C++11)删除gcc在以下(伪)代码上产生的警告: 我希望避免添加假的返回-1(从未到达),因为这会使代码更难阅读。使用c++11可以使用[[noreturn]] 像这样: [[noreturn]] void throw_invalid() { throw std::invalid_argument( "invalid" ); } int foo(const char * str) { if( str ) return 42;
我希望避免添加假的
返回-1
(从未到达),因为这会使代码更难阅读。使用c++11可以使用[[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
是非无效函数,并且是触发错误的函数,但是需要该属性的函数是throw\u invalid
。将throw\u invalid
设置为noreturn
将告诉编译器,每当使用函数throw\u invalid
的代码路径时,foo
也不会返回。根据我的理解,在进行任何计算之前,您需要首先确保参数有效。尽管如此,我相信您可以通过相应地重写代码来克服这个问题
在您的示例中,类似于:
int foo(const char * str)
{
// Make sure that str is valid
if( str == NULL ) throw_invalid();
return 42;
}
对于GCC,您可以将
noreturn
attrubute添加到方法中:
void throw_invalid()
#ifdef __GNUC__
__attribute__ ((noreturn))
#else
// something here for Visual Studio
#endif
{
throw std::invalid_argument( "invalid" );
}
手册上说:
noreturn
关键字告诉编译器假定“致命”
无法返回。然后,它可以优化,而不考虑会发生什么
如果函数确实返回,则发生。这使得代码稍微好一些。
更重要的是,它有助于避免未初始化的错误警告
变量
在以下情况下,noreturn
关键字不会影响异常路径:
这适用于:标记为noreturn的函数仍可能返回到
通过抛出异常或调用longjmp
调用调用方
我没有你的其他编译器的经验,所以不能填补那里的空白;抱歉。@默认情况下,非void函数是
foo()
,编译器会发出警告,因为它不返回值。但是,由于throw\u invalid()
永不返回,因此永远无法到达此函数的结尾。这个答案中提供的解决方案告诉编译器这一事实,这样它就可以避免虚假警告。这只适用于普通示例,但在某些情况下,您无法以这种方式重新排序代码(不降低效率或以其他方式修改代码)。
int foo(const char * str)
{
// Make sure that str is valid
if( str == NULL ) throw_invalid();
return 42;
}
void throw_invalid()
#ifdef __GNUC__
__attribute__ ((noreturn))
#else
// something here for Visual Studio
#endif
{
throw std::invalid_argument( "invalid" );
}