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)?
If the thing you are returning by reference is logically part of your this object, independent of whether it is physically embedded within your this object, then a const method needs to return by const reference or by value, but not by non-const reference.
Because the reference is a const reference the function body cannot directly change the value of that object. This has a similar property to passing by value where the function body also cannot change the value of the object that was passed in, in this case because the parameter is a copy.
Use Nullable Reference Types If the developer really needs to return a null value from the method (in 99% of cases this is not necessary), the return type can be marked as a nullable reference type (the feature was introduced in C# 8.0).
(C++) const return typeThe value of a return type that is declared const cannot be changed. This is especially useful when giving a reference to a class's internals (see example #0), but can also prevent rarer errors (see example #1). Use const whenever possible [1-7].
There are two idiomatic ways to handle this:
end
).Or
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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With