std :: unique_ptr与std :: map [英] std::unique_ptr with std::map

查看:145
本文介绍了std :: unique_ptr与std :: map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 std :: map ,其中的键是 std :: shared_ptr< Foo> ,值是 std :: unique_ptr< Bar> ,其中 Foo Bar 是不同于第三方库的类.我正在使用这个 std :: map 对象作为内存中的缓存.

I have a std::map where the key is std::shared_ptr<Foo> and the value is std::unique_ptr<Bar> where Foo and Bar are very different classes from a third-party library. I am using this std::map object as an in-memory cache.

我想知道将给定 Bar 传递给 std :: unique_ptr 的最佳方法是从该方法中插入新条目,然后从该方法返回.code>是否已经构建?

I am wondering what the best way of inserting a new entry into this map will be and then returned from a method, given that the Bar passed into the std::unique_ptr will already be constructed?

我目前有以下内容:

class SomeClass
{
public:

    const Bar* TryGetBarValue(std::shared_ptr<Foo> foo)
    {
        auto it = _cache.find(foo);

        if(it == _cache.end())
        {
            Bar bar = ThirdPartLibrary::CreateBar();
            _cache.emplace(foo, std::make_unique<Bar>(bar));
            return _cache.rbegin()->second.get();
        }

        //return result as raw ptr from unique_ptr
        return it->second.get();
    }

private:
    std::map<std::shared_ptr<Foo>, std::unique_ptr<Bar>> _cache;
}

编辑

感谢昆汀提供的答案,现在这是我的实现方式

Thanks to the answer provided by Quentin, this is now my implementation:

class SomeClass
{
public:

    const Bar* TryGetBarValue(std::shared_ptr<Foo> foo)
    {
        auto it = _cachedImages.find(texture);

        if (it != _cachedImages.end())
        {
            return it->second.get();
        }

        return _cachedImages.emplace(
                std::move(texture), 
                std::make_unique<sf::Image>(texture->copyToImage())
            ).first->second.get(); 
        }

private:
    std::map<std::shared_ptr<Foo>, std::unique_ptr<Bar>> _cache;
}

感谢您的所有帮助!

推荐答案

返回_cache.rbegin()-> second.get(); 不能满足您的要求,因为std :: map 不会追加元素,而是 sorts 元素.但是 emplace 会将迭代器返回到它刚刚插入的迭代器,因此您只需要:

return _cache.rbegin()->second.get(); does not do what you want, as std::map does not append elements but sorts them. However emplace returns an iterator to what it just inserted, so you only need:

return _cache.emplace(foo, std::make_unique<Bar>(bar))->first->second.get();

或者甚至,由于实际上不需要存储和复制 Bar ,因此您也可以牺牲 foo :

Or even, since you don't actually need to store and copy the Bar, and you can also sacrifice foo:

return _cache.emplace(
    std::move(foo),
    std::make_unique<Bar>(ThirdPartLibrary::CreateBar())
)->first->second.get();

我也将亲自翻转(it == _cache.end())条件,以使其早日返回,但这只是一个口味问题.

I'd also personally flip the (it == _cache.end()) condition to make it an early return, but that's just a matter of taste.

否则,你的东西对我来说看起来很好.

Otherwise, what you have looks good to me.

这篇关于std :: unique_ptr与std :: map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆