假设我有以下功能:
Thingy& getThingy(int id)
{
for ( int i = 0; i < something(); ++i )
{
// normal execution guarantees that the Thingy we're looking for exists
if ( thingyArray[i].id == id )
return thingyArray[i];
}
// If we got this far, then something went horribly wrong and we can't recover.
// This function terminates the program.
fatalError("The sky is falling!");
// Execution will never reach this point.
}
编译器通常会对此抱怨,说“并非所有控制路径都返回值”。这在技术上是正确的,但是不返回值的控制路径会在函数结束之前中止程序,因此在语义上是正确的。有没有办法告诉编译器(在我的例子中是VS2010,但我对其他编译器也很好奇)出于此检查的目的,要忽略某个控制路径,而不完全抑制警告或返回无意义的虚拟值函数末尾的值?
您可以注释该函数fatalError
(它的声明)让编译器知道它永远不会返回。
在 C++11 中,这将类似于:
[[noreturn]] void fatalError(std::string const&);
在 C++11 之前,您具有编译器特定的属性,例如 GCC 的:
void fatalError(std::string const&) __attribute__((noreturn));
或 Visual Studio 的:
__declspec(noreturn) void fatalError(std::string const&);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)