从类方法C 0x返回unique_ptr
如果我的类SomeType有一个方法从地图返回一个元素(使用键)说
std::unique_ptr<OtherType> get_othertype(std::string name) { return otMap.find(name); } 这会确保调用者会收到指向地图中指针而不是副本的指针吗?这样做是否可以,或者它会尝试调用复制构造函数(并且因为它已被删除而失败)因为它被返回了吗? 假设我必须使用unique_ptr作为我的地图项目. 更新:: 在尝试实现代码之后,似乎unique_ptr和std:map /:pair在gcc 4.4.4中不能一起工作,对只是不喜欢unique_ptr作为类型参数. (见Can’t create map of MoveConstructibles). 我将ptr更改为std :: shared_ptr并且一切正常. 我想我可以使用与共享指针相同的代码? 解决方法
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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |