我有一个简单的对象缓存:
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_;
};
返回类型是从缓存中检索时的常量引用。
但是,在找不到 key 的情况下,将返回对临时对象的 const 引用,并导致调用代码出现未定义的行为。
如何解决将常量引用返回到临时引用的问题?
我的一些想法:
- 插入并返回指针(缓存取得所有权),nullptr 表示未找到
- 提供 ObjectCache::contains 以便调用代码可以在访问之前进行检查
- 维护一个静态或空的 Object 成员,并在找不到时返回对该成员的引用
最佳答案
理想的解决方案是维护当前缓存但返回指向引用的指针:
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 nullptr;
}
void insert(const std::string &key, const Object &object)
{
cache_[key] = object;
}
private:
std:map<std::string, Object> cache_;
};
这具有避免在堆上创建对象和内存管理的额外好处,但允许调用代码使用未找到的 nullptr。
关于c++ - 如何避免将 const-ref 返回到缓存中的临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46425683/