0

Okay so I have this code:

GameObject Game::findObjectWithTag(const std::string& tag) {
    for (auto gameObject : m_objectList) {
        if (gamObjPtr->tag() == tag)
            return *gamObjPtr;
    }
}

All conditions must have a return is not required in c++, so I am just wondering how to tell when this function has not worked(the string inputed had not match). I cannot return NULL or a nullptr like in other languages so what do I do?

  • 4
    Why can't you return a null pointer? Just return a pointer, not a value. It's not clear why a `find` function would copy the found object, so maybe you don't really want to return by value. But even a pointer is overkill here; since `m_objectList` is iterable, you can just unconditionally return the result of `std::find_if()` with a suitable comparator - thus making 4 lines into 1 - then getting `m_objectList.end()` means no match was found. If you really do want to return by value i.e. copy, then search `std::optional`. – underscore_d Nov 23 '20 at 17:33
  • the duplicate asks for `std::experimental::optional`, meanwhile it is just `std::optional` (since c++17) – 463035818_is_not_an_ai Nov 23 '20 at 17:34
  • 3
    You can return an iterator to the found element or the `[c]end()` iterator of the collection, like `std::find[_if]()` does. Alternatively, you can return a `std::optional`. – EOF Nov 23 '20 at 17:35
  • 2
    taking your question literally it asks for `std::optional`, but I agree with others, that you should rather look at how `std::find_if` does it. Returning the end iterator is a widely accepted idiom to indicate "not found" – 463035818_is_not_an_ai Nov 23 '20 at 17:36
  • @underscore_d I have just seen alot of people returning by value is preferred over pointer. –  Nov 23 '20 at 17:38
  • 1
    on the other hand if not finding the element is an exceptional case, you could throw – 463035818_is_not_an_ai Nov 23 '20 at 17:40
  • 1
    I'm sure you misunderstood, there will be situations where one is preferred over another and vice versa. – Passer By Nov 23 '20 at 17:44
  • 1
    @JackDelahunt returning by value makes a new copy, that is rarely preferred, especially for a find function. Returning things like strings by value makes sense, but returning game objects by value, usually less so. Return by reference or pointer instead. – Remy Lebeau Nov 23 '20 at 17:45
  • For fun, there is still another way... `std::optional< std::reference_wrapper >`. That's for people who really don't want to use pointers or iterators. I do use this sometimes. – underscore_d Nov 23 '20 at 17:50

0 Answers0