拥有typedef std :: map <boost :: shared_ptr <my_class>,my_description&gt;如何回归&amp;我的函数中的shared_ptr?</boost :: shared_ptr <my_class>

时间:2011-07-15 00:32:32

标签: c++ boost shared-ptr

所以我有这样的功能:

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;
}

我需要它来返回这样的boost :: shared_ptr,它不是ptr的副本,而是指向地图内部的指针。我的主要目标是用结果做这样的事情

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

然后在地图上用其他ptr重新分配指针。 (我不需要删除对象,因为它可以在我清理map ptr时在其他一些线程中使用。)

1 个答案:

答案 0 :(得分:1)

好的,我不知道你真正想做什么,但这是一个骷髅的想法:

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);