mercredi 1 février 2017

Return std::pair

I have the following piece of code which searches a map of type std::map<int, const CustomClass&>. I would like to return a "failure" case object if the item is not found in the map.

I went through the discussion in Returning a “NULL reference” in C++?

Using std::pair with a bool to indicate if the item is valid or not (note: requires that SomeResource has an appropriate default constructor and is not expensive to construct):

std::pair<SomeResource, bool> SomeClass::getSomething(std::string name) {
    std::map<std::string, SomeResource>::iterator it = content_.find(name);
    if (it != content_.end()) 
        return std::make_pair(*it, true);  
    return std::make_pair(SomeResource(), false);

}

but since my CustomClass is an Abstract Base Class I cannot instantiate it !

Are there any better ways to circumvent this ? I imagine returning a pointer to the class object might allow it to be mutable. I would like to keep the returned object immutable.

My code sample is shown below -

std::pair<const NpBaseTest::NpBaseTest&, bool> NpTestMgr::find(const UID& p_uid) const
{
    auto search = m_pending.find(p_uid);
    if(search != m_pending.end())
        return std::make_pair(*search, true);
    return std::make_pair(NpBaseTest(), false);
}

Aucun commentaire:

Enregistrer un commentaire