Sounds like you need a boost::optional<Foo&>
return value (optional references). Your code should look like this:
class YourCache {
std::map<std::string, Foo> _cache;
public:
boost::optional<Foo&> FooByName(const std::string& name)
{
std::map<std::string, Foo>::iterator itr = _cache.find(name);
if(_cache.end() == itr)
return boost::none;
return boost::optional<Foo&>(itr->second);
}
};
- getter doesn't throw :)
- respects the already existing implementation of _cache (you don't have to change it to store smart pointers - or pointers in general)
- gives no direct access to memory in client code (like returning Foo* would)
- expresses the intent in the best way ("the return value is optional/could be missing")
- offers an explicit and natural interface in client code:
For example:
// client code:
if (boost::optional<Foo&> result = YourCache.FooByName("FOO")) {
// only run if result is in cache
result->bar();
}