How-to return a const std::vector<Object *const>?

后端 未结 5 1337
北恋
北恋 2021-01-25 06:37

I have a class with a container (containing pointer) as a member:

MyClass{
private:
   std::vector _VecMyObjs;
public:
   const std::vector

        
5条回答
  •  不要未来只要你来
    2021-01-25 07:12

    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).

    1. 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).

    2. 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.

提交回复
热议问题