How to return “not found” when return value is const reference

强颜欢笑 提交于 2019-12-23 09:09:05

问题


I have a problem that when I use something like this:

const MyList& my_list = getListForThisRegion(/*region ID, ...*/);

I dont know what to return when no value is found.

My problem is that I would like to have a way to signal (when returning value from getListForThisRegion) "value not found" to the caller. If I was returning a pointer, I could return nullptr, but I don't know how to do it with references. All I can think of is having some static member not_found of type MyList, and returning a reference to it, but it seems ugly.

And yes, I can't return value because lists are "fat" and often used.

EDIT: ton of great answers , but exception is not an acceptable solution because the number of times it would be raised is high (the percentage nbNotFound/nbCalls is high).
EDIT2: regarding boost::optional - how complicated it is to master? I mean does it require some non obvious knowledge (non obvious= something that is not simply knowing the syntax)?


回答1:


There are two idiomatic ways to handle this:

  • Change your interface to return a type that has the ability to refer to nothing (e.g. a pointer that can be null, an iterator to end).

Or

  • Throw an exception if the item isn't found.

Returning a dummy object is a bit hacky, and you don't gain anything over returning a pointer as you still have to check the result against a special value (null or the dummy object).




回答2:


How about rewriting the function to take reference to "returnValue" where you put the list to return? Then the function can return boolean value indicating found/ not found.

bool getListForThisRegion(/*region ID, ...*/, MyList& ret_list);



回答3:


I'd write exception class (hierarchy, if needed) and throw an exception for such case.




回答4:


I only see two possibilities: either you have a special member in the MyList class declaring that an instance is "null" (not set) or you could throw an exception.




回答5:


You could follow std::map's lead, and insert a default constructed list into your container, and return a reference to that. Obviously, this depends on there not being a semantic difference between a default list, and a list that isn't there at all.

You can also add a query function that searches for a particular region, and returns true if it has a list, and false otherwise. Then, you can throw an exception in your accessor safe in the knowledge that it will not be a common occurrence.



来源:https://stackoverflow.com/questions/7847336/how-to-return-not-found-when-return-value-is-const-reference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!