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

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返回到临时文件的问题?

我有一些想法:
  • 插入和返回指针(缓存获取所有权),nullptr表示找不到
  • 提供ObjectCache::包含,因此调用代码可以在访问
  • 之前进行检查
  • 维护静态或空对象成员,并在找不到
  • 时返回对该成员的引用

    最佳答案

    理想的解决方案是维护当前缓存,但返回指向引用的指针:

    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/

    10-11 22:43
    查看更多