On Dec 8, 12:51 pm, Jeff Flinn <TriumphSprint2...@hotmail.com> wrote:
Andrea Crotti wrote:
James Kanze <james.ka...@gmail.com> writes:
The simplest solution is to return a pointer to the map's
contents, or NULL if the value isn't there, e.g.:
int const* Cont::getValue(int idx) const
{
std::map<int, int>::const_iterator result
= content.find(idx);
return result == content.end()
? NULL
: &result->second;
}
and:
int const* i = obj.getValue(idx);
if ( i != NULL ) {
...
}
I would do that in C but I don't think it looks nice in C++...
To avoid the memory allocation and ownership issues use boost::optional.
There aren't any memory allocation and ownership issues. I use
the Fallible idiom (on which boost/optional is based) a lot, but
in this case, a pointer seems simpler and more appropriate:
a pointer is the standard idiom for a fallible reference.
#include <boost/optional.hpp>
typedef boost::optional<int> optional_int;
optional_int Cont::getValue(int idx) const
{
std::map<int, int>::const_iterator itr = content.find(idx);
return (itr != cont.end())? itr->second : optional_int();
}
and:
if(optional_int i = obj.getValue(idx)) // safe bool idiom
{
int x = *i + 123; // deref for value
}
Which doesn't work in general, since the returned value (if
found) is supposed to be a reference to the element, not a copy
of it.
Andrea's original posting was returning by value. That's what I addressed.
I don't know if boost would support boost::optional<int&>. When