的模式unique_ptr
是所有权转让。如果你unique_ptr
从一个函数返回一个对象,那么unique_ptr
系统中的任何其他人都不可能引用同一个对象。
那是你要的吗?我对此表示高度怀疑。当然,您可以简单地返回一个原始指针:
OtherType* get_othertype(const std::string& name)
{
return otMap.find(name)->second.get();
}
因此,客户端可以访问该对象,但地图仍然拥有它。
如果在名称下找不到条目,上述解决方案相当脆弱。在这种情况下,更好的解决方案是抛出异常或返回空指针:
#include <stdexcept>
OtherType* get_othertype(const std::string& name)
{
auto it = otMap.find(name);
if (it == otMap.end()) throw std::invalid_argument("entry not found");
return it->second.get();
}
OtherType* get_othertype(const std::string& name)
{
auto it = otMap.find(name);
return (it == otMap.end()) ? 0 : it->second.get();
}
为了完整起见,这里是 Anthony 返回参考的建议:
OtherType& get_othertype(const std::string& name)
{
auto it = otMap.find(name);
if (it == otMap.end()) throw std::invalid_argument("entry not found");
return *(it->second);
}
以下是您如何返回unique_ptr
对地图内部的引用,但让我们将其设为对 const 的引用,这样客户端就不会意外修改原始内容:
unique_ptr<OtherType> const& get_othertype(const std::string& name)
{
auto it = otMap.find(name);
if (it == otMap.end()) throw std::invalid_argument("entry not found");
return it->second;
}