3

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?

11
  • 1
    You could return static_cast<Foo const *>(myFoos.data()) if the result will only be used for a short time, before you mutate the vector... Commented Apr 27, 2013 at 17:55
  • 4
    Return a pair of const iterators to begin and end. In C++11 teach for how to iterate over it as well. Commented Apr 27, 2013 at 17:58
  • 1
    @H2CO3: then you add a const Foo to your cast-to vector, and still later access it via the original vector and try changing it... BOOM. Commented Apr 27, 2013 at 17:58
  • 1
    Or use a type to wrap the pointers, where operator* and operator-> have adequate const versions. Commented Apr 27, 2013 at 18:07
  • 1
    Add a method to access the objects, instead of the vector: 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. Commented Apr 27, 2013 at 18:11

1 Answer 1

0

Just add operator[] const to your Foo class:

const Foo& operator[] (size_t i) const {
    // you may add some range checking here
    return *myFoos[i];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.