gpt4 book ai didi

std::map 中的 C++ std::unique_ptr

转载 作者:行者123 更新时间:2023-11-30 00:50:57 27 4
gpt4 key购买 nike

这是:

std::unique_ptr<sf::Texture> texture;
texture = std::move(textureMap.at(id));
return *texture;

像这样吗?

auto found = textureMap.find(id);
return *found->second;

textureMap 是:

std::map<ID, std::unique_ptr<sf::Texture>>

如果是,什么是更好的解决方案?

谢谢!

最佳答案

第一个将指针移出 map ,以便在函数返回时销毁它指向的对象。如果函数返回引用,则该引用将无效。它还会在映射中留下一个空指针,如果您尝试取消引用它,稍后会导致问题 - 代码假定指针不为空,因此如果它们是空的,则会出现未定义的行为。

第二个将指针留在原处,因此对象得以保留。如果函数返回引用,则该引用仍然有效。但是,如果找不到 key ,它就会有未定义的行为;它应该检查 found != textureMap.end(),或者返回 *textureMap.at(id) 如果找不到 key ,它将抛出。

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

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