What function signature should I use to return a reference to an object that may not exist?

I am writing a simple container class in C ++ that looks like a map that stores objects indexed by a key. I would like to provide an access function, for example:

V& getValue(const K &key);

where i return the value of reference .

But I also wanted to handle the case where the key / value is missing and may return some status to the user (there may be some reasons why I do not want me to contact the caller through some type of status).

I suppose I could do the following, but to call it, I would need a V object that needs to be constructed before this function can be called, and I'm just going to copy the internal V object to the one passed by reference, so which seems bad.

Status getValue(const K &key, V& v);

I could also do:

V &getValue(const K &key, Status &s);

But for some reason this seems a bit awkward, as the focus moves away from the status and users may forget to check it (but maybe this is not my problem).

So is there a function similar to a function

Status getValue(const K &key, V& v);

without a dummy V object that must be constructed before it is called? You cannot pass a link to a link. I suppose I could use pointers, and I'm happy to do it, but it is less desirable to create an easy to use and reasonable function.

Any thoughts?

+5
7

bool contains(const K &key), , , . ( , , , , )

, , . , ?

+2

V& getValue(const K &key) , Status.

, ( ), , . .

+2

boost::optional , boost. boost::optional :

boost::optional<MyClass &> getValue(const K &key)
+1

3 :

  • "wrapper", V & , ( V *).
  • .
  • , throw , .

.

+1

boost::variant<V &, Status> () boost::variant<std::reference_wrapper<V>, Status>.

0

std:: map:

std::pair<iterator,bool> getValue(const K& key);

value , bool , .

0

, : boost::optional<boost::ref<V> >, , , , .

However, I would not suggest this interface. Standard containers already have an interface that solves this problem, namely returning iterators, not values. I would suggest just using the iterator interface (it should not be a real full-scale iterator) and returning end/ one for the end to indicate that it is not found, and is not returned by reference or not. The more you make your container interface look like a standard container, the more opportunities there are for using standard algorithms and plug it in wherever you want as a replacement.

0
source

All Articles