如何从boost ptr_vector中检索引用?

时间:2010-09-21 22:38:28

标签: c++ boost ptr-vector

我有两个类:Object类和ObjectManager类。 ObjectManager类通过ptr_vector容器存储“Objects”。在某些情况下,我需要检索对这些存储指针的引用,以对它们执行单独的操作。我该怎么做?

Compilable Pseudo Code:

#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>

class Object
{
public:
  int m_Id;
  Object(int id) : m_Id(id) { }
};

class ObjectManager
{
private:
  typedef boost::shared_ptr<Object> ObjectPtr;
  typedef boost::ptr_vector<Object> ObjectVectorPtr;
  typedef ObjectVectorPtr::iterator ObjectIt;

  ObjectVectorPtr vector_;

  void AddObject(Object *obj) {
    vector_.push_back(obj);
  }

  ObjectPtr FindObject(int id) {
    for (ObjectIt it = vector_.begin(); it != vector_.end(); it++) {
      if (it->m_Id == id) {
        // Found the object...How to return a shared_ptr reference to it?
        // The line below is invalid, obviously:
        // cannot convert parameter 1 from 'Object' to 'const boost::shared_ptr<T> &'
        return *it;
      }
    }

    // We could not find anything.
    return ObjectPtr();
  }
};

基本上我希望ObjectManager保留所有权,但我也希望其他类能够获得对象的引用,根据正在进行的操作使用该对象的调用方法,然后继续。

2 个答案:

答案 0 :(得分:2)

将容器转换为使用shared_ptr作为成员:

#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>

class Object
{
public:
  int m_Id;
  Object(int id) : m_Id(id) { }
};

class ObjectManager
{
private:
  typedef boost::shared_ptr<Object> ObjectPtr;
  typedef std::vector<ObjectPtr> ObjectVectorPtr;
  typedef ObjectVectorPtr::iterator ObjectIt;

  ObjectVectorPtr vector_;

  void AddObject(ObjectPtr& obj) {
    vector_.push_back(obj);
  }

  ObjectPtr FindObject(int id) {
    for (ObjectIt it = vector_.begin(); it != vector_.end(); ++it) {
      if (it->get()->m_Id == id) {
        // Found the object - return a shared_ptr reference to it
        return ObjectPtr(*it);
      }
    }

    // We could not find anything.
    return ObjectPtr();
  }
};

btw - 首选++it vs it++以避免额外构造,如果容器变大,请不要使用此类匹配 - 切换到std::map<int, ObjectPtr>m_id为密钥,或std::set具有适当定义的less函数。

如果我是超级迂腐的,我会建议您调用std::find_if替换您的查找循环,并在Object::m_id上匹配谓词...

答案 1 :(得分:0)

您无法返回shared_ptr,因为该对象最初并未创建为共享对象 - 引用计数甚至是多少?

但是,您可以非常轻松地返回Object *:

Object* FindObject(int id) {
    for (ObjectIt it = vector_.begin(); it != vector_.end(); it++) {
      if (it->m_Id == id) {
        // Found the object...How to return a shared_ptr reference to it?
        // The line below is invalid, obviously:
        // cannot convert parameter 1 from 'Object' to 'const boost::shared_ptr<T> &'
        return &*it;
      }
    }