假设我有以下功能:
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&);
关于c++ - 我可以告诉编译器考虑关闭关于返回值的控制路径吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12146772/