I have a class with a container (containing pointer) as a member:
MyClass{
private:
std::vector _VecMyObjs;
public:
const std::vector
I'm not sure std::vector
(vector of constant pointers) is really what you want : I believe you mean std::vector
(vector of pointer to constant objects).
The "first level" of constness (pointer constness) is naturally achieved by returning a constant reference on the vector. Only const_iterator
can be obtained from a const vector, so you have a guarantee that the pointers won't be modified (but pointees can be).
The "second level" of constness (pointee constness) is harder to obtain. Either return a new instance of a vector as already pointed out by others :
return std::vector(_VecMyObjs.begin(), _VecMyObjs.end());
Or, if applicable, try to look into the Boost Pointer Container library (and most notably ptr_vector) which offers, among other things, correct constness propagation :
Propagates constness such that one cannot modify the objects via a const_iterator.
You have to understand that returning a const reference on a vector guarantees that it cannot be modified (no insertion, deletion, or modification of its value). So, in most cases, returning a const std::vector
is the way to go because if does not involve any copying. The issue here is really specific to container of pointers, where constness of the values does not provide constness of the pointees.