简体   繁体   English

eclipse c ++中的“控制到达非空函数的末尾”警告,但没有编译时或运行时错误

[英]“control reaches end of non-void function” warning in eclipse c++ but no compile- or run-time errors

Here's my code: 这是我的代码:

Composer& Database::GetComposer (string in_last_name)
{   
    for (int i = 0; i < next_slot_; i++)
    {
        if (composers_[i].last_name() == in_last_name)
             return composers_[i];
    }
}

The idea is to iterate over an array of Composer objects and return a reference to the object whose last_name field matches "in_last_name." 想法是遍历Composer对象的数组,并返回其last_name字段与“ in_last_name”匹配的对象的引用。 I understand what the warning is telling me, namely that it's possible that the function won't return anything (if, say, the user provides an invalid last name). 我知道警告告诉我的内容,即该函数可能不返回任何内容(例如,如果用户提供了无效的姓氏)。 My question is, how can I avoid this? 我的问题是,如何避免这种情况? I tried adding "return 0" and "return NULL" after the for loop and it wouldn't compile. 我尝试在for循环后添加“ return 0”和“ return NULL”,但无法编译。 Should this method throw an exception if it finds nothing? 如果找不到任何内容,此方法是否应该引发异常?

Your function is declared to return a Composer& , that is, a reference to a Composer . 声明您的函数以返回Composer& ,即对Composer的引用。 If your function fails to return a suitable reference, and the caller tries to use the return value for something, undefined behaviour will result. 如果您的函数未能返回合适的引用,并且调用方尝试将返回值用于某些内容,则将导致未定义的行为。

If your function may legitimately fail to find what it's looking for, you may want to change the return type to a pointer instead of a reference . 如果您的函数可能合法地找不到所需的内容,则可能需要将返回类型更改为指针而不是引用 That would give you the option to return NULL : 这将使您可以选择返回NULL

Composer* Database::GetComposer (string in_last_name)
{   
    for (int i = 0; i < next_slot_; i++)
    {
        if (composers_[i].last_name() == in_last_name)
             return &composers_[i];
    }
    return NULL;
}

Alternatively, you could throw an exception when your function fails to find the target. 或者,当函数无法找到目标时,您可能会引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM