开发者

can function return 0 as reference

开发者 https://www.devze.com 2023-01-04 06:40 出处:网络
I have this snippet of the code Account& Company::findAccount(int id){ for(list<Account>::const_iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i){
I have this snippet of the code

Account& Company::findAccount(int id){
        for(list<Account>::const_iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i){
            if(i->nID == id){
         开发者_StackOverflow中文版       return *i;
            }
        }
        return 0;
    }

Is this right way to return 0 if I didn't find appropriate account? cause I receive an error:

no match for 'operator!' in '!((Company*)this)->Company::findAccount(id)'

I use it this way:

if(!(findAccount(id))){
            throw "hey";
          }

thanks in advance


There is no such thing as a null reference. The standard says:

A reference shall be initialized to refer to a valid object or function. [ Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior.


You cannot return a "null reference" in C++, because there is no such concept in this language.

If either an Account or no Account can be the result, one way to do it is to return an Account *.


Why don't you use a standard algorithm like std::find_if.

Edit: Explanation of find_if.

Here is the reference for find_if algorithm. http://cplusplus.com/reference/algorithm/find_if/

bool isEqual(int id1, int id2) {
   return id1 == id2;
}

void foo() {
    std::list<Account> accountList;
    // Fill this list here.

    list<Account>::iterator it = std::find_if(accountList.begin(), accountList.end(), bind(isEqual, idYouSearch, _1));

    Account ac = *it;
}

You might need additional includes for bind and _1 placeholder. Propably there is a std Predicate for isEqual and you could use this instead.


No, this is not possible. It looks like the function may have been changed from returning a pointer (Account*) to returning a reference (Account&).

You cannot return 0/null as a reference, you will have to change the design of the function. Maybe reverting to Account* as return type.

If you only use it in an if-statement like that, you could change it to returning a std::bool. But the current signature suggests other usage patterns.


Another way (except for Account*) would be to return special Account::empty object, and/or test using account.IsEmpty().

0

精彩评论

暂无评论...
验证码 换一张
取 消