搜索通过unique_ptr的向量搜索的find函数的返回值

Jan*_*art 3 c++ iterator vector unique-ptr c++11

我正在搜索对象的unique_ptr向量.例如,通过用户输入名称来解析该对象.因此,这种类型的功能:

std::unique_ptr<obj> const& objectForName(std::string name) {
    std::vector<std::unique_ptr<obj>>::iterator it;
    it = std::find_if(objVec.begin(), objVec.end(), [name](const std::unique_ptr<obj>& object) -> bool {return object->getName() == name; });
    if (it != objVec.end())
      return *it;
    else
      throw(Some_Exception("Exception message"));
}
Run Code Online (Sandbox Code Playgroud)

我想在向此向量添加对象的情况下重用此函数.函数应调用此函数,并且在未找到它的情况下返回可由调用函数检查的内容,而不是抛出异常.调用函数可以在检查返回值时抛出异常.我的问题是可以返回什么可以检查调用函数?

Jam*_*nze 7

只需返回一个指针:

obj const* objectForName( std::string const& name )
{
    std::vector<std::unique_ptr<obj>>::iterator results
            = std::find_if(
                objVec.begin(),
                objVec.end(),
                [&]( std::unique_ptr<obj> const& object ) {
                            return object->getName == name; } );
    return results != objVec.end()
        ? results->get()
        : nullptr;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你把头撞到墙上时头部受伤,不要再将头撞在墙上,它会停止疼痛.使用`delete`正是反对"智能指针的范例",而不是这个. (3认同)
  • 不,问题是删除,而不是原始指针. (3认同)