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

后端 未结 5 1225
北恋
北恋 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:15

    Assuming the vector of the non-const pointers resides somewhere during the entire lifetime that you are going to use the const-version so you don't need a copy, and if there a lot of them so you don't want to copy the vector, you are better off returning some kind of wrapper object that is custom made to only give the user const-access.

    The address of the first element of the vector will be T** and you can't cast that to const T** (correctly) nor can you cast it to const T*const * (which would be safe but the language does not allow it).

    If you were allowed to convert the latter it would be perfect for creating a read-only view.

提交回复
热议问题