在这种情况下我会回报什么?

Pet*_*ter 0 c++ pointers reference std shared-ptr

我将发布我的代码然后解释我的查询:

typedef std::shared_ptr<SEntity> Entity;

//Scene_Ids is an enum
static std::map<Scene_Ids, std::vector<Entity> > m_scene_entities;

std::shared_ptr<SEntity>& SEntityManager::getEntity(const std::string& entity_name)
{
    int counter = 0;

    for (auto iter = m_scene_entities.begin(); iter != m_scene_entities.end(); ++iter)
    {
        if (iter->second[counter]->getId() == entity_name)
            return iter->second[counter];

        counter++;
    }

    //What would I return if the entity couldn't be found?
}
Run Code Online (Sandbox Code Playgroud)

代码基本上解释了这一切.我有一个方法,如果在地图内的std :: vector中找到"实体",它将返回对它的std :: shared_ptr类型的引用.但是,由于我没有返回指针,我无法返回nullptr.在失败的情况下我能回报什么?

另外,我知道std :: shared_ptr意味着在几个不同的地方有副本.为此,我真的需要返回一个引用,还是可以按值返回它?

谢谢!

Dav*_*men 6

返回迭代器而不是迭代器的内容.这样你可以判断你是否到了最后.