c++ - 如何避免将 const-ref 返回到缓存中的临时文件

标签 c++ caching maps

我有一个简单的对象缓存:

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/

相关文章:

c++ - Assimp Faces 都有索引 (0,1,2)

c++ - 指向 lambda 函数的函数指针相等

android - 如何将 Google Maps plus 代码转换为 Lng 和 Lat 坐标

c++ - 结构或类中的 friend 功能

c++ - 如何使 SWIG 绑定(bind)类在 Lua 中使用运算符?

caching - 如何在 Flutter 中更改图像缓存的缓存持续时间(包 : flutter_cached_network_image & flutter_cache_manager)

google-maps - 使用 Google Maps API 查找最近点

javascript - 用于查看带有叠加层的大图像( map )的 HTML/Javascript 选项

linux - nginx 作为缓存代理不缓存任何东西

caching - 如何通过 ActiveModel::Serializers (v0.10.0.rc1) 使用缓存键的动态值