Search code examples
c++coding-style

C++ what is the idiomatic way to avoid pointers?


I have a method which takes const ref to a set. I want to call it and m.b. pass a set to it. If I have it. So first I see if I have a set:

const auto& it = mapOfSets.find("token");
if (it != std::end(mapOfSets)) {
  myFunction(it.second);
} else {
  MySetType emptySet;
  myFunction(emptySet);
}

What is an idiomatic way of doing this? I don't like the above because call to myFunction is repeated twice and there is a few other arguments, so there is some unnecessary code duplication.

The C programmer in me just wants to change the function to accept a pointer and pass nullptr if set is not found, but i feel that C++ is all about avoiding pointers now?..


Solution

  • If you write a helper function to find a set in the map then you can return a reference to a special empty set in the case that you did not find anything:

    const MySetType& find(const MyMapType& mapOfSets, const std::string& key) {
        auto it = mapOfSets.find(key);
        if (it != std::end(mapOfSets)) {
            return it->second;
        }
        static const MySetType emptySet;
        return emptySet;
    }
    

    Then your calling code is simply:

    myFunction(find(mapOfSets, "token"));