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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With