Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure constness of the returning vector<unique_ptr>

Tags:

c++

c++11

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

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 because the elements of the vector are not const, so caller still can change the individual elements, e.g.

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

My solution is to insert const to the vector:

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

But this leads to a boring implementation of get_const_objs() which I copy 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 iterator interface to MyClass. Is there any other solution?

I have a restriction: BOOST is not available. But I like to know BOOST solution if really there is good one just using standard.

like image 744
my_question Avatar asked Oct 31 '22 18:10

my_question


1 Answers

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

You cannot do it, So you don't have to worry!

Since objs is const vector<> &, the element of this vector is also treated as const. Therefore, you cannot "move" it; can you move const objects?

like image 111
ikh Avatar answered Nov 15 '22 05:11

ikh