How to ensure the consistency of the returned vector <unique_ptr>

I asked a related question here . Now it is a little thinner.

Here is the code:

class MyClass {
  public:
    const vector<unique_ptr<MyObject> >& get_const_objs() const;

  private:
    vector<unique_ptr<MyObject>> m_objs;
};

My intention is that the returned vector from get_const_objs () is read-only, but the problem is that the elements of the vector are not constants, so the caller can still modify individual elements, for example.

const vector<unique_ptr<MyObject>>& objs = pMyClass->get_const_objs();
unique_ptr<MyObject> p = move(objs[0]);

My solution is to insert const into the vector:

const vector<const unique_ptr<MyObject> >& get_const_objs() const;

But this leads to a boring implementation of get_const_objs (), which copies each element to a new vector:

const vector<const unique_ptr<MyObjects>>& MyClass::get_const_objs() const
{
  vector<const unique_ptr<MyObjects>> ret;
  for (const auto &obj : my_objs) {
    ret.push_back(obj);
  }
  return ret;
}

Yes, I can add an iterator interface to MyClass. Is there any other solution?

I have a limitation: BOOST is not available. But I like to know the BOOST solution if there really is a good one that just uses the standard.

+4
3
const vector<unique_ptr<MyObject>>& objs = pMyClass->get_const_objs();
unique_ptr<MyObject> p = move(objs[0]);

, !

objs - const vector<> &, const. "" ; const?

+1

A () - std::vector<const MyObject*> std::unique_ptr.

std::vector<const MyObject*> get_const_objs() const
{
    std::vector<const MyObject*> res;
    res.reserve(my_objs.size());
    for (const auto& obj : my_objs) {
        res.push_back(obj.get());
    }
    return res;
}

, .

0

, const MyObject &

class ConstObjectIter {
public:
    ...
    const MyObject& operator* () const { return **m_it; }
    const MyObject* operator->() const { return &**this; }
    ConstIter& operator++() { ++m_it; return *this; }
    ...
private:
    std::vector<std::unique_ptr<MyObject> >::const_iterator m_it, m_end;
}

m_it, m_end m_objs.begin(), m_objs.end()

0

All Articles