c++ - 我可以告诉编译器考虑关闭关于返回值的控制路径吗?

标签 c++ visual-studio-2010 g++ warnings

假设我有以下功能:

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/

相关文章:

c++ - 使用 GLEW、GLFW 和 g++ 编译在 OS X 10.10 下启用 OpenGL 4.1

c++ - 奇怪的 undefined reference `vtable

linux -/usr/bin/ld : client: hidden symbol `__dso_handle'

c++ - 我可以将 Visual C++ Redistributable 2010 和/或 DirectX 10 安装到特定文件夹吗?

c++ - 我怎么能算出函数 ispunct 没有的一些标点符号

c++ - 使用 std::string 和 char* 的最烦人的解析实例

java - Java 1.6 与 C++ 的性能对比?

c++ - ncurses newwin() 和 mvwin() 未按预期运行

c++ - 重新编译前 Visual Studio 2010 文件修改警告对话框

c# - 从C#中的异常“ArguementException未由用户代码处理”中获取更多详细信息