I have a class with a member vector of pointers to objects. Now I want an accessor method to return a const reference to this vector. I also want the caller method to be unable to edit the objects pointed to by the vector's pointers, i.e. the pointers should point to const objects. Here is my erroneous code:
class Foo
{
private:
vector<Foo*> myFoos;
public:
const vector<const Foo*> &getMyFoos(void)
{
return myFoos; //Doesn't work since vector<Foo*> cannot be cast to vector<const Foo*>
}
}
I have seen answers to similar questions where the solution is to make a copy of the vector myFoos where the copy is of the correct type. Is there anyway to do this without making a copy, since the myFoos vector may be very large?
static_cast<Foo const *>(myFoos.data())if the result will only be used for a short time, before you mutate the vector...forhow to iterate over it as well.const Footo your cast-tovector, and still later access it via the originalvectorand try changing it... BOOM.operator*andoperator->have adequateconstversions.Foo const* getFoo(size_t i) const { return myFoos[i]; }-- Also a method to get the size. If your pointers cannot be null, return a reference instead.