Search code examples
c++boostshared-ptr

Having typedef std::map<boost::shared_ptr<my_class>,my_description> how to return & shared_ptr from my function?


So I have such function:

boost::shared_ptr<my_class> get_class_by_name(std::string name)
{
    typedef std::map<boost::shared_ptr<my_class>, my_description> map_t;
    BOOST_FOREACH(map_t::value_type it, some_object.class_map)
    {
        my_description descr = it.second;
        if(descr.name == name)
        {
            return it.first;
        }
    }
    throw std::runtime_error("Class with such name was not found map not found!");
    boost::shared_ptr<my_class> null;
    return null;
}

I need it to return such boost::shared_ptr that it would be not a copy of ptr but pointer that is inside of the map. my main objective is to do something like this with result

boost::shared_ptr<my_class> result = get_class_by_name(name);
boost::shared_ptr<my_class> null;
result  =  null; //(or result.reset();)

and than reasign pointer in map with some other ptr. (I do not need to delet the object because it can be used in some other thread at the time I clean up map ptr.)


Solution

  • OK, I don't know what you're really trying to do, but here's a skeleton idea:

    typedef std::shared_ptr<my_class> my_class_ptr;
    typedef std::map<my_class_ptr, my_description> my_map_t;
    
    struct FindByName
    {
      FindByName(cosnt std::string & s) : name(s) { };
      inline bool operator()(const my_description & d) { return name == d.name; }
    private:
      std::string name;
    };
    
    /* Usage: */
    
    my_map_t m = /* ... */
    my_map_t::iterator it = std::find_if(m.begin(), m.end(), FindByName("bob"));
    
    if (it != m.end()) m.erase(it);