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

后端 未结 5 1368
北恋
北恋 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 06:59

    Aside from changing the signature to remove the const from the vector (as it's a copy of the vector), I'm assuming that you don't want people outside to modify the contents, as a result, make a const pointer , i.e.

    vector ACI_CALL MyClass::GetVecMyObjs()
    {
       return vector(_VecMyObjs.begin(), _VecMyObjs.end());
    }
    

    Now the returned vector is a copy, which contain const pointer (which means you can't modify the pointed object via this pointer) - well that's the agreement, there's nothing preventing someone from const_casting that away (using that is UB anyways!)

    If you really want to prevent modifications, return a copy (or clone of each object) in the vector.

提交回复
热议问题