【发布时间】:2017-09-26 11:46:57
【问题描述】:
我有一个简单的对象缓存:
class ObjectCache
{
public:
ObjectCache() {}
const Object& object(const std::string &key) const
{
auto it = cache_.find(key);
if (it != cache_.end())
{
return it->second;
}
return Object(); // const-ref to temporary
}
void insert(const std::string &key, const Object &object)
{
cache_[key] = object;
}
private:
std:map<std::string, Object> cache_;
};
从缓存中检索时的返回类型是 const ref。
但是,如果未找到密钥,则返回临时的 const ref 并导致调用代码的未定义行为。
如何解决将 const ref 返回到临时对象的问题?
我的一些想法:
- 插入并返回指针(缓存取得所有权),nullptr 表示未找到
- 提供 ObjectCache::contains 以便调用代码可以在访问前检查
- 维护静态或空 Object 成员,并在找不到时返回对它的引用
【问题讨论】:
-
第四个解决方案是使用
std::optional或booost::optiona来包装引用。 -
你可以使用 std::optional.
-
选项 5) 如果找不到对象,则抛出
ItemNotFoundException。选项 6) 使类可迭代,如果没有找到则返回end(),否则返回对象的迭代器。 -
我看不到
optional的真正好处。 -
当然
std::optional可以保存引用。这就是std::ref的意义所在。