gpt4 book ai didi

c++ - std::unique_ptr 与 std::map

转载 作者:行者123 更新时间:2023-11-30 04:51:22 25 4
gpt4 key购买 nike

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

我想知道将新条目插入此映射然后从方法返回的最佳方法是什么,前提是 Bar传入了std::unique_ptr已经建成了吗?

我目前有以下内容:

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;
}

编辑

感谢 Quentin 提供的答案,现在这是我的实现:

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;
}

感谢您的帮助!

最佳答案

return _cache.rbegin()->second.get(); 没有做您想要的,因为 std::map 没有 append 元素,但对它们进行排序。然而 emplace 返回一个迭代器到它刚刚插入的内容,所以你只需要:

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

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

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

我也会亲自翻转 (it == _cache.end()) 条件以使其提前返回,但这只是个人喜好问题。

否则,我觉得你的东西不错。

关于c++ - std::unique_ptr 与 std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54828756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com