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

2056 views c++

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)) {
} else {
  MySetType 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?..

answered question

The type of it.second is MySetType, right?

yes hopefully it is

C++ is about avoiding raw owning pointers. Using the pointer like you would a reference is still okay.

You could make a helper that returns optional<reference_wrapper<const T>> for a lookup and use its value_or function. Rather awkward without the native support for references, though.

1 Answer


You can use the conditional operator:

myFunction(it != mapOfSets.end() ? it->second : {});

I don't think there is an idiomatic way though.

posted this

Have an answer?


Please login first before posting an answer.