我有一个简单的对象缓存:
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引用,并导致未定义的行为调用代码。
我该如何解决将const ref返回到临时文件的问题?
我有一些想法:
最佳答案
理想的解决方案是维护当前缓存,但返回指向引用的指针:
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/