我可以告诉编译器考虑到关于返回值的封闭控制路径吗? [英] Can I tell the compiler to consider a control path closed with regards to return value?

查看:57
本文介绍了我可以告诉编译器考虑到关于返回值的封闭控制路径吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我具有以下功能:

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,但我也很好奇),为了进行此检查,必须忽略某个控制路径,而不必完全抑制警告或返回无意义的虚拟对象函数末尾的值是什么?

Compilers will typically complain at this, saying that "not all control paths return a value". Which is technically true, but the control paths that don't return a value abort the program before the function ends, and are therefore semantically correct. Is there a way to tell the compiler (VS2010 in my case, but I'm curious about others as well) that a certain control path is to be ignored for the purposes of this check, without suppressing the warning completely or returning a nonsensical dummy value at the end of the function?

推荐答案

您可以注释函数 fatalError (其声明),以使编译器知道它永远不会返回.

You can annotate the function fatalError (its declaration) to let the compiler know it will never return.

在C ++ 11中,这类似于:

In C++11, this would be something like:

[[noreturn]] void fatalError(std::string const&);

在C ++ 11之前的版本中,您具有编译器专有的属性,例如GCC:

Pre C++11, you have compiler specific attributes, such as GCC's:

void fatalError(std::string const&) __attribute__((noreturn));

或Visual Studio:

or Visual Studio's:

__declspec(noreturn) void fatalError(std::string const&);

这篇关于我可以告诉编译器考虑到关于返回值的封闭控制路径吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆