Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

c++ - How to return "not found" when return value is const reference

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...