Search code examples
c++vectorreturnreturn-value

How to return Null as reference in C++?


I've made some minimal code

vector<int> items = {1, 2, 5, 0, 7};
int& getAtSafe(unsigned n) {
    if (n < items.size() && items[n] != 5) return items[n];
    else // ???
}

But how to return something as null when we can't find needed item?
P.S. Original task is searching item with property equal to.

Exception variants not accepted. I do not need to pause the program.
As an example, user types index, and each time when it's wrong, the user gets "Bad input"


Solution

  • C++ has value semantics. There are nullptrs but there is no null value. A reference always references something. Ergo, there cannot be a reference to null.

    Several options you have:

    • throw an exception. Your argument for rejecting them is moot. std::vector::at does exactly that (but I suppose your code is just an example for a more general situation)
    • return a pointer that can be nullptr (not recommended, because then you put the resonsibility on handling it correctly on the caller)
    • return a std::optional. Again this forces the caller to handle the case of "no value returned" but in contrast to returning a nullptr the caller gets a well-designed interface that is hard to use wrong.
    • return an iterator. end is often used to signal "element not found" throughout the standard library, so there will be little surprise if you do the same.
    • perhaps this is not just an example for a different situation, then you should use std::vector::at instead of your handwritten function and be done with it.

    P.S. Original task is searching item with property equal to.

    You should use std::find to find an item in a container. It returns end of the container when the element cannot be found.