vendredi 21 avril 2017

proper way to return a large object or indicate that it is not found

What is the idiomatic C++ way of doing this? I have a method which looks like this:

LargeObject& lookupLargeObject(int id) {
  return largeObjects[id];
}

This is wrong, because if you call this with a non-existent id it will create a new instance of large object and put it into the container. I don't want that. I don't want to throw an exception either. I want the return value to signal that object wasn't found (as it is a more or less normal situation). So my options are either a pointer or an optional. Pointer I understand and like, but it feels like C++ doesn't want to me use pointers any more. So on to optionals. I will return an optional and then the caller looks like this:

std::optional<LargeObject> oresult = lookupLargeObject(42);
LargeObject result;
if (oresult) {
  result = *oresult;
} else {
  // deal with it
}

Is this correct? It feels kind of crappy because it seems that I'm creating 2 copies of the LargeObject here? Once when returning the optional and once when extracting it from optional into result. Gotta be a better way?

Aucun commentaire:

Enregistrer un commentaire